-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathawspy.py
executable file
·1456 lines (1285 loc) · 65.5 KB
/
awspy.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/python3
import argparse
import boto3
from botocore.exceptions import BotoCoreError
import sys
import yaml
import datetime
import ipaddress
import re
import os
import warnings
from urllib3.exceptions import InsecureRequestWarning
from flask import request
import shlex
def AwsFinder(resource_id, profiles = None, regions = None, verify_ssl = True):
if profiles:
profiles = [profiles]
else:
profiles = boto3.Session().available_profiles
if regions:
regions = [regions]
else:
regions = ["us-east-1", "us-east-2", "us-west-1", "us-west-2"]
# Regular expression for UUID pattern (for DXGW)
uuid_pattern = r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
verify = None if verify_ssl else False
for profile in profiles:
for region in regions:
find_session = boto3.Session(profile_name=profile, region_name=region)
find_ec2 = find_session.client('ec2', verify=verify)
find_dx = find_session.client('directconnect', verify=verify)
# Check if resource_id is an IP address or subnet
try:
ip = ipaddress.ip_address(resource_id)
if isinstance(ip, ipaddress.IPv4Address):
response = find_ec2.describe_network_interfaces(
Filters=[{'Name': 'addresses.private-ip-address', 'Values': [resource_id]}]
)
if not response["NetworkInterfaces"]:
continue
elif isinstance(ip, ipaddress.IPv6Address):
response = find_ec2.describe_network_interfaces(
Filters=[{'Name': 'ipv6-addresses.ipv6-address', 'Values': [resource_id]}]
)
if not response["NetworkInterfaces"]:
continue
# Process and return the response for IP address
return f"Network ip {resource_id} found in profile: {profile}, region: {region}"
except ValueError:
# Not a valid subnet, continue with other resource checks
pass
except BotoCoreError:
# Error in describe_subnets, continue to next region
continue
# Check if resource_id is a subnet
try:
cidr = ipaddress.ip_network(resource_id, strict=False)
if cidr.version == 4:
response = find_ec2.describe_subnets(
Filters=[{'Name': 'cidrBlock', 'Values': [resource_id]}]
)
else:
response = find_ec2.describe_subnets(
Filters=[{'Name': 'ipv6-cidr-block-association.ipv6-cidr-block', 'Values': [resource_id]}]
)
if not response["Subnets"]:
continue
# Process and return the response for subnet
return f"Subnet {resource_id} found in profile: {profile}, region: {region}"
except ValueError:
# Not a valid subnet, continue with other resource checks
pass
except BotoCoreError:
# Error in describe_subnets, continue to next region
continue
try:
# Check for different AWS resource types
if resource_id.startswith("eni-"):
find_ec2.describe_network_interfaces(NetworkInterfaceIds=[resource_id])
elif resource_id.startswith("subnet-"):
find_ec2.describe_subnets(SubnetIds=[resource_id])
elif resource_id.startswith("rtb-"):
find_ec2.describe_route_tables(RouteTableIds=[resource_id])
elif resource_id.startswith("tgw-rtb-"):
find_ec2.describe_transit_gateway_route_tables(TransitGatewayRouteTableIds=[resource_id])
elif resource_id.startswith("lgw-rtb-"):
result = find_ec2.describe_local_gateway_route_tables(LocalGatewayRouteTableIds=[resource_id])
if not result["LocalGatewayRouteTables"]:
continue
elif resource_id.startswith("pl-"):
find_ec2.describe_managed_prefix_lists(PrefixListIds=[resource_id])
elif resource_id.startswith("vpc-"):
find_ec2.describe_vpcs(VpcIds=[resource_id])
elif resource_id.startswith("sg-"):
find_ec2.describe_security_groups(GroupIds=[resource_id])
elif resource_id.startswith("i-"):
find_ec2.describe_instances(InstanceIds=[resource_id])
elif resource_id.startswith("acl-"):
find_ec2.describe_network_acls(NetworkAclIds=[resource_id])
# Check for Direct Connect Gateway (UUID format)
elif resource_id.startswith("dxcon-"):
result = find_dx.describe_connections(connectionId=resource_id)
if not result["connections"]:
continue
elif resource_id.startswith("dxvif-"):
result = find_dx.describe_virtual_interfaces(virtualInterfaceId=resource_id)
if not result["virtualInterfaces"]:
continue
elif re.match(uuid_pattern, resource_id):
result = find_dx.describe_direct_connect_gateways(directConnectGatewayId=resource_id)
if not result["directConnectGateways"]:
continue
else:
return f"Resource {resource_id} is not valid"
return f"Resource {resource_id} found in profile: {profile}, region: {region}"
except Exception as e:
continue
return f"Resource {resource_id} not found"
class AwsFetcher:
def __init__(self, profile, region, verify_ssl = True):
verify = None if verify_ssl else False
self.session = boto3.Session(profile_name=profile, region_name=region)
self.ec2_client = self.session.client('ec2', verify=verify)
self.dx_client = self.session.client('directconnect', verify=verify)
self.log_client = self.session.client('logs', verify=verify)
def get_instance_name(self, instance_id):
try:
# Fetching the instance information
response = self.ec2_client.describe_instances(InstanceIds=[instance_id])
# Extracting the first instance from the response
reservations = response.get('Reservations', [])
if reservations:
instances = reservations[0].get('Instances', [])
if instances:
instance = instances[0]
# Extracting the Name tag from the instance tags
for tag in instance.get('Tags', []):
if tag['Key'] == 'Name':
return tag['Value']
return None
except:
return None
def get_flow_logs_by_vpc(self, vpc_id):
flow_logs_response = self.ec2_client.describe_flow_logs(
Filters=[
{'Name': 'resource-id', 'Values': [vpc_id]}
]
)
active_flow_logs = []
for flow_log in flow_logs_response['FlowLogs']:
if flow_log['LogDestinationType'] == 'cloud-watch-logs' and flow_log['FlowLogStatus'] == 'ACTIVE':
active_flow_logs.append(f"{flow_log['FlowLogId']} - {flow_log['LogGroupName']}")
return active_flow_logs
def get_flowlog_information(self, fl_id, eni_id, hours, filter_arg):
try:
end_time = datetime.datetime.now(datetime.timezone.utc)
start_time = end_time - datetime.timedelta(hours=hours)
start_timestamp_ms = int(start_time.timestamp() * 1000)
end_timestamp_ms = int(end_time.timestamp() * 1000)
flow_logs = self.ec2_client.describe_flow_logs(FlowLogIds=[fl_id])
log_group_name = flow_logs['FlowLogs'][0]['LogGroupName'] if flow_logs['FlowLogs'] else None
streams = self.log_client.describe_log_streams(
logGroupName=log_group_name,
logStreamNamePrefix=eni_id
)
log_stream_name = streams['logStreams'][0]['logStreamName'] if streams['logStreams'] else None
flowlog = self.log_client.get_log_events(
logGroupName=log_group_name,
logStreamName=log_stream_name,
startFromHead=True,
startTime=start_timestamp_ms,
endTime=end_timestamp_ms
)
if filter_arg:
events = [event for event in flowlog['events'] if filter_arg in event['message']]
else:
events = flowlog["events"]
formatted_messages = {}
for event in events:
if 'message' in event and isinstance(event['message'], str):
message = event["message"]
parts = message.split()
event_time = datetime.datetime.fromtimestamp(event["timestamp"]/1000, tz=datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
src_ip = parts[3]
dst_ip = parts[4]
src_port = parts[5]
dst_port = parts[6]
protocol_num = parts[7]
start_time = int(parts[10])
action = parts[12]
status = parts[13]
if not event_time in formatted_messages:
formatted_messages[event_time] = []
formatted_message = f"{src_ip} {src_port} -> {dst_ip} {dst_port} - Protocol: {protocol_num} - {action} - {status}"
formatted_messages[event_time].append(formatted_message)
return formatted_messages
except:
raise ValueError('No flowlogs found for the given identifiers.')
def get_eni_information(self, eni_identifier):
if eni_identifier.startswith('eni-'):
response = self.ec2_client.describe_network_interfaces(NetworkInterfaceIds=[eni_identifier])
else:
ip = ipaddress.ip_address(eni_identifier)
if isinstance(ip, ipaddress.IPv4Address):
response = self.ec2_client.describe_network_interfaces(Filters=[{'Name': 'addresses.private-ip-address', 'Values': [eni_identifier]}])
elif isinstance(ip, ipaddress.IPv6Address):
response = self.ec2_client.describe_network_interfaces(Filters=[{'Name': 'ipv6-addresses.ipv6-address', 'Values': [eni_identifier]}])
try:
eni_info = response.get('NetworkInterfaces', [None])[0]
except:
raise ValueError("No ENI found for the given identifier.")
return eni_info
def get_vpc_association_information(self, vpc_id):
# Fetch Transit Gateway attachments for the VPC
tgw_attachments_response = self.ec2_client.describe_transit_gateway_attachments(Filters=[{'Name': 'resource-id', 'Values': [vpc_id]}])
lgw_attachments_response = self.ec2_client.describe_local_gateway_route_table_vpc_associations(Filters=[{'Name': 'vpc-id', 'Values': [vpc_id]}])
tgw_attachments = tgw_attachments_response.get('TransitGatewayAttachments', [])
lgw_attachments = lgw_attachments_response.get('LocalGatewayRouteTableVpcAssociations', [])
response = {}
for attachment in tgw_attachments:
if 'Association' in attachment and 'TransitGatewayRouteTableId' in attachment['Association']:
response[attachment['TransitGatewayId']] = attachment['Association']['TransitGatewayRouteTableId']
for attachment in lgw_attachments:
response[attachment["LocalGatewayId"]] = attachment["LocalGatewayRouteTableId"]
return response
def get_vpc_information(self, vpc_id):
# Fetch VPC information
vpc_response = self.ec2_client.describe_vpcs(VpcIds=[vpc_id])
vpc_info = vpc_response.get('Vpcs', [None])[0]
if not vpc_info:
raise ValueError("No VPC found for the given ID.")
# Fetch Transit Gateway attachments for the VPC
tgw_attachments_response = self.ec2_client.describe_transit_gateway_attachments(Filters=[{'Name': 'resource-id', 'Values': [vpc_id]}])
tgw_attachments = tgw_attachments_response.get('TransitGatewayAttachments', [])
tgw_associations = []
for attachment in tgw_attachments:
if 'Association' in attachment and 'TransitGatewayRouteTableId' in attachment['Association']:
tgw_associations.append({
'tgw': attachment['TransitGatewayId'],
'tgw-route-table': attachment['Association']['TransitGatewayRouteTableId']
})
return {
'vpc': {
'id': vpc_info.get('VpcId'),
'cidr-blocks': [assoc['CidrBlock'] for assoc in vpc_info.get('CidrBlockAssociationSet', []) if assoc.get('CidrBlock')],
'ipv6-cidr-blocks': [assoc['Ipv6CidrBlock'] for assoc in vpc_info.get('Ipv6CidrBlockAssociationSet', []) if assoc.get('Ipv6CidrBlock')],
'TGW-associations': tgw_associations
},
}
def get_subnet_information(self, subnet_id):
response = self.ec2_client.describe_subnets(SubnetIds=[subnet_id])
try:
subnet_info = response.get('Subnets', [None])[0]
except:
raise ValueError("No Subnet found for the given Subnet ID.")
return subnet_info
def get_subnet_information_by_id_or_cidr(self, identifier):
if identifier.startswith('subnet-'):
response = self.ec2_client.describe_subnets(SubnetIds=[identifier])
else:
try:
# Check if the identifier is an IPv4 or IPv6 CIDR block
cidr = ipaddress.ip_network(identifier, strict=False)
if cidr.version == 4:
response = self.ec2_client.describe_subnets(Filters=[{'Name': 'cidr-block', 'Values': [identifier]}])
else:
response = self.ec2_client.describe_subnets(Filters=[{'Name': 'ipv6-cidr-block-association.ipv6-cidr-block', 'Values': [identifier]}])
except ValueError:
raise ValueError("Invalid subnet identifier. It must be a subnet ID or a valid CIDR block.")
try:
subnet_info = response.get('Subnets', [None])[0]
except:
raise ValueError("No Subnet found for the given identifier.")
return subnet_info
def get_route_table_information(self, subnet_id):
response = self.ec2_client.describe_route_tables(Filters=[{'Name': 'association.subnet-id', 'Values': [subnet_id]}])
route_tables = response.get('RouteTables', [])
# If there are multiple route tables associated, this will get the first one
if route_tables:
return route_tables[0].get('RouteTableId')
else:
return None
def get_lgw_route_table_information_by_id(self, lgw_rt_id):
response = self.ec2_client.search_local_gateway_routes(
LocalGatewayRouteTableId=lgw_rt_id)
try:
routes = response.get('Routes', [])
except:
raise ValueError("No LGW Route Table found for the given ID.")
return routes
def get_tgw_route_table_information_by_id(self, tgw_rt_id):
response = self.ec2_client.search_transit_gateway_routes(
TransitGatewayRouteTableId=tgw_rt_id,
Filters=[{'Name': 'state', 'Values': ['active', 'blackhole']}]
)
try:
routes = response.get('Routes', [])
except:
raise ValueError("No TGW Route Table found for the given ID.")
return routes
def get_route_table_information_by_id(self, route_table_id):
response = self.ec2_client.describe_route_tables(RouteTableIds=[route_table_id])
try:
route_table_info = response.get('RouteTables', [None])[0]
except:
raise ValueError("No Route Table found for the given ID.")
return route_table_info
def get_tag_value(self, tags, key):
for tag in tags:
if tag['Key'] == key:
return tag['Value']
return None
def get_security_group_information(self, sg_id):
try:
response = self.ec2_client.describe_security_groups(GroupIds=[sg_id])
sg_info = response.get('SecurityGroups', [None])[0]
if not sg_info:
raise ValueError("No Security Group found for the given ID.")
return sg_info
except Exception as e:
print(f"Error retrieving security group information: {e}")
return None
def get_network_acl_information(self, acl_id):
try:
response = self.ec2_client.describe_network_acls(NetworkAclIds=[acl_id])
acl_info = response.get('NetworkAcls', [None])[0]
if not acl_info:
raise ValueError("No Network ACL found for the given ID.")
return acl_info
except Exception as e:
print(f"Error retrieving network ACL information: {e}")
return None
def get_instance_information(self, instance_identifier):
try:
# Check if identifier is an instance ID or name
filters = [{'Name': 'instance-id', 'Values': [instance_identifier]}]
if not instance_identifier.startswith('i-'):
filters = [{'Name': 'tag:Name', 'Values': [instance_identifier]}]
response = self.ec2_client.describe_instances(Filters=filters)
instances = response.get('Reservations', [])[0].get('Instances', [])
if not instances:
return "Instance not found"
instance_info = instances[0]
instance_id = instance_info['InstanceId']
status_checks = {
'instance_status': 'unknown',
'system_status': 'unknown'
}
try:
status = self.ec2_client.describe_instance_status(InstanceIds=[instance_id])
instance_status = status['InstanceStatuses'][0]
status_checks['instance_status'] = instance_status['InstanceStatus']['Status']
status_checks['system_status'] = instance_status['SystemStatus']['Status']
except:
pass
instance_name = next((tag['Value'] for tag in instance_info['Tags'] if tag['Key'] == 'Name'), 'Unnamed')
custodian = next((tag['Value'] for tag in instance_info['Tags'] if tag['Key'] == 'custodian-ignore'), False)
state = instance_info['State']["Name"]
vpc_id = instance_info['VpcId']
try:
iam_info = instance_info['IamInstanceProfile']
iam_role = iam_info['Arn'].split('/')[-1]
except:
iam_role = None
# Create a list of ENI dictionaries
enis_list = [{
'position': eni['Attachment']['DeviceIndex'],
'id': eni['NetworkInterfaceId'],
'subnet': eni['SubnetId'],
"Security Groups": [group['GroupId'] for group in eni.get('Groups', [])],
'ips': [ip['PrivateIpAddress'] for ip in eni['PrivateIpAddresses']],
} for eni in instance_info['NetworkInterfaces']]
# Sort the list based on the position
enis_sorted_list = sorted(enis_list, key=lambda x: x['position'])
# Create a dictionary from the sorted list
enis_sorted = {eni['id']: {k: v for k, v in eni.items() if k != 'id'} for eni in enis_sorted_list}
return {
'id': instance_id,
'name': instance_name,
'vpc': vpc_id,
'iam': iam_role,
'state': state,
'status': status_checks,
'Keep after shutdown': custodian,
'enis': enis_sorted
}
except:
raise ValueError("No ec2 found for the given identifier.")
def get_acl_by_subnet(self, subnet_id):
try:
# Fetching all network ACLs
response = self.ec2_client.describe_network_acls(Filters=[
{'Name': 'association.subnet-id', 'Values': [subnet_id]}
])
acls = []
for acl in response.get('NetworkAcls', []):
acls.append(acl.get('NetworkAclId'))
return acls[0]
except:
raise ValueError("No acl found for the given identifier.")
def get_acl_by_id(self, subnet_id):
try:
# Fetching all network ACLs
response = self.ec2_client.describe_network_acls(Filters=[
{'Name': 'association.subnet-id', 'Values': [subnet_id]}
])
acls = []
for acl in response.get('NetworkAcls', []):
acl_info = {
'id': acl.get('NetworkAclId'),
'is_default': acl.get('IsDefault'),
'entries': acl.get('Entries', []),
'associations': acl.get('Associations', [])
# Add other relevant details here
}
acls.append(acl_info)
return acls
except:
raise ValueError("No acl found for the given identifier.")
def format_eni_output(self, eni_info, subnet_info):
subnet_tags = subnet_info.get('Tags', [])
route_table_id = self.get_route_table_information(subnet_info.get('SubnetId'))
acl = self.get_acl_by_subnet(subnet_info.get("SubnetId"))
flowlogs = self.get_flow_logs_by_vpc(subnet_info.get('VpcId'))
instance = eni_info.get('Attachment', {}).get('InstanceId', 'Not attached')
if instance.startswith("i-"):
instance_name = self.get_instance_name(instance)
if instance_name:
instance = f"{instance_name} ({instance})"
output = {
"ENI": {
"ID": eni_info.get('NetworkInterfaceId'),
"description": eni_info.get('Description'),
"instance": instance,
"ips": [ip['PrivateIpAddress'] for ip in eni_info.get('PrivateIpAddresses', [])] +
[ipv6['Ipv6Address'] for ipv6 in eni_info.get('Ipv6Addresses', [])],
"Security Groups": [group['GroupId'] for group in eni_info.get('Groups', [])],
"flowlogs": flowlogs
},
"subnet": {
"ID": subnet_info.get('SubnetId'),
"cidr": subnet_info.get('CidrBlock'),
"ipv6_cidr": next((assoc['Ipv6CidrBlock'] for assoc in subnet_info.get('Ipv6CidrBlockAssociationSet', []) if assoc.get('Ipv6CidrBlock') and assoc.get('Ipv6CidrBlockState', {}).get('State') == 'associated'), None),
"vpc": subnet_info.get('VpcId'),
"route-table": route_table_id,
"Vrouter": self.get_tag_value(subnet_tags, 'VrouterName'),
"Vrouter-Position": self.get_tag_value(subnet_tags, 'VrouterInterfacePos'),
"Vrf": self.get_tag_value(subnet_tags, 'VRFName'),
"acl": acl
}
}
return output
def format_subnet_output(self, subnet_info):
subnet_tags = subnet_info.get('Tags', [])
route_table_id = self.get_route_table_information(subnet_info.get('SubnetId'))
enis = self.get_enis_by_subnet(subnet_info.get('SubnetId'))
acl = self.get_acl_by_subnet(subnet_info.get("SubnetId"))
output = {
"subnet": {
"ID": subnet_info.get('SubnetId'),
"cidr": subnet_info.get('CidrBlock'),
"ipv6_cidr": next((assoc['Ipv6CidrBlock'] for assoc in subnet_info.get('Ipv6CidrBlockAssociationSet', []) if assoc.get('Ipv6CidrBlock') and assoc.get('Ipv6CidrBlockState', {}).get('State') == 'associated'), None),
"vpc": subnet_info.get('VpcId'),
"route-table": route_table_id,
"Vrouter": self.get_tag_value(subnet_tags, 'VrouterName'),
"Vrouter-Position": self.get_tag_value(subnet_tags, 'VrouterInterfacePos'),
"Vrf": self.get_tag_value(subnet_tags, 'VRFName'),
"acl": acl
},
"enis": enis
}
return output
def format_route(self, route):
nexthop = route.get('GatewayId') or \
route.get('EgressOnlyInternetGatewayId') or \
route.get('TransitGatewayId') or \
route.get('NetworkInterfaceId') or \
route.get('VpcPeeringConnectionId') or \
route.get('NatGatewayId') or \
route.get('LocalGatewayId') or \
route.get('CarrierGatewayId') or \
route.get('CoreNetworkArn') or \
route.get('VpcEndpointId') or \
route.get('InstanceId') or \
route.get('GatewayLoadBalancerEndpointId') or \
route.get('VirtualPrivateGatewayId') or \
'local' # 'local' is used if none of the above are found
destination = route.get('DestinationCidrBlock') or \
route.get('DestinationIpv6CidrBlock') or \
route.get('DestinationPrefixListId')
if nexthop.startswith(("tgw-", "lgw-")):
nexthop = f"{nexthop} to {self.vpc_info[nexthop]}"
if destination.startswith("pl-"):
return {f"{destination} via {nexthop}": [', '.join(map(str, self.get_managed_prefix_list_entries(destination)))]}
else:
return f"{destination} via {nexthop}"
def get_eni_by_sg(self, sg_id):
try:
response = self.ec2_client.describe_network_interfaces(Filters=[{
'Name': 'group-id',
'Values': [sg_id]
}])
enis = []
for eni in response.get('NetworkInterfaces', []):
eni_id = eni.get('NetworkInterfaceId')
enis.append(eni_id)
return enis
except:
raise ValueError("Error retrieving instances by sg_id")
def get_dxcon_information(self, dxcon_id):
try:
dxcon = self.dx_client.describe_connections(
connectionId=dxcon_id
)
dxvifs = self.dx_client.describe_virtual_interfaces(connectionId=dxcon_id)
response = {"dxcon": dxcon.get('connections', [None])[0], "dxvifs": dxvifs.get("virtualInterfaces", [None])}
return response
except:
raise ValueError("Error retrieving DXCON information")
def get_dxvif_information(self, dxvif_id):
try:
dxvif = self.dx_client.describe_virtual_interfaces(
virtualInterfaceId=dxvif_id
)
dxgw_id = dxvif.get('virtualInterfaces', [None])[0]['directConnectGatewayId']
dxgw = self.dx_client.describe_direct_connect_gateways(directConnectGatewayId=dxgw_id)
response = {"dxvif": dxvif.get('virtualInterfaces', [None])[0], "dxgw": dxgw.get("directConnectGateways", [None])}
return response
except:
raise ValueError("Error retrieving DXVIF information")
def get_dxgw_information(self, dxgw_id):
try:
dxgw = self.dx_client.describe_direct_connect_gateways(
directConnectGatewayId=dxgw_id
)
attachments = self.dx_client.describe_direct_connect_gateway_attachments(
directConnectGatewayId=dxgw_id
)
associations = self.dx_client.describe_direct_connect_gateway_associations(
directConnectGatewayId=dxgw_id
)
response = {"dxgw": dxgw.get('directConnectGateways', [None])[0], "attachments": attachments.get('directConnectGatewayAttachments', [None]), "associations": associations.get("directConnectGatewayAssociations", [None])}
return response
except:
raise ValueError("Error retrieving DXGW information")
def get_transit_gateway_information(self, tgw_id):
try:
# Check if identifier is an instance ID or name
filters = [{'Name': 'transit-gateway-id', 'Values': [tgw_id]}]
if not tgw_id.startswith('tgw-'):
filters = [{'Name': 'tag:Name', 'Values': [tgw_id]}]
response = self.ec2_client.describe_transit_gateways(Filters=filters)
tgw = response.get('TransitGateways', [None])[0]
# Format the TGW information
formatted_tgw_info = {
'id': tgw.get('TransitGatewayId'),
'name': self.get_tag_value(tgw.get('Tags', []), 'Name'),
'description': tgw.get('Description'),
'options': tgw.get('Options', {})
}
return formatted_tgw_info
except:
raise ValueError("Error retrieving TGW")
def get_enis_by_subnet(self, subnet_id):
try:
response = self.ec2_client.describe_network_interfaces(Filters=[
{'Name': 'subnet-id', 'Values': [subnet_id]}
])
enis = []
for eni in response.get('NetworkInterfaces', []):
eni_info = {
'id': eni.get('NetworkInterfaceId'),
'description': eni.get('Description'),
"ips": [ip['PrivateIpAddress'] for ip in eni.get('PrivateIpAddresses', [])] +
[ipv6['Ipv6Address'] for ipv6 in eni.get('Ipv6Addresses', [])],
# Add other relevant details here
}
enis.append(eni_info)
return enis
except:
raise ValueError("Error retrieving instances by subnet_id")
def get_managed_prefix_list_entries(self, prefix_list_id):
try:
response = self.ec2_client.get_managed_prefix_list_entries(PrefixListId=prefix_list_id)
return [entry['Cidr'] for entry in response.get('Entries', [])]
except:
raise ValueError("Error retrieving managed prefix list entries")
def format_dxcon_output(self, response):
# Extracting Direct Connect connection information
dxcon_info = {
'id': response['dxcon']['connectionId'],
'name': response['dxcon']['connectionName'],
'region': response['dxcon']['region'],
'bw': response['dxcon']['bandwidth'],
'jumbo frame': response['dxcon']['jumboFrameCapable'],
'device': response['dxcon']['awsDevice'],
'logical device': response['dxcon']['awsLogicalDeviceId'],
'vifs': []
}
# Process each VIF associated with the connection
for vif in response['dxvifs']:
vif_info = {
'id': vif['virtualInterfaceId'],
'connection id': vif['connectionId'],
'vlan': vif['vlan'],
'Amazon AS': vif['amazonSideAsn'],
'dxgw-id': vif.get('directConnectGatewayId', 'N/A'), # Using 'N/A' if not present
'peers': []
}
# Add peer information for each VIF
for peer in vif['bgpPeers']:
peer_info = {peer['bgpPeerId']: {
peer['bgpPeerId']: {
'asn': peer['asn'],
'authKey': peer['authKey'],
'addressFamily': peer['addressFamily'],
'amazonAddress': peer['amazonAddress'],
'customerAddress': peer['customerAddress'],
'bgpPeerState': peer['bgpPeerState'],
'bgpStatus': peer['bgpStatus'],
# Include additional BGP peer information if necessary
}
}}
vif_info['peers'].append(peer_info)
dxcon_info['vifs'].append(vif_info)
# Find the DXGW name using the DXGW ID from the DXVIF
if 'dxgw' in response and response['dxgw']:
dxgw_id = response['dxvifs'][0].get('directConnectGatewayId')
dxgw_info = next((gw for gw in response['dxgw'] if gw['directConnectGatewayId'] == dxgw_id), {})
dxcon_info['dxgw-name'] = dxgw_info.get('directConnectGatewayName', 'N/A')
return dxcon_info
def format_dxvif_output(self,vif_data):
# Extracting Virtual Interface (VIF) information
vif_info = {
'id': vif_data['dxvif']['virtualInterfaceId'],
'connection id': vif_data['dxvif']['connectionId'],
'vlan': vif_data['dxvif']['vlan'],
'Amazon AS': vif_data['dxvif']['amazonSideAsn'],
'region': vif_data['dxvif']['region'],
'dxgw-id': vif_data['dxvif']['directConnectGatewayId']
}
# Find the DXGW name using the DXGW ID
dxgw_name = next((gw['directConnectGatewayName'] for gw in vif_data['dxgw'] if gw['directConnectGatewayId'] == vif_data['dxvif']['directConnectGatewayId']), None)
vif_info['dxgw-name'] = dxgw_name
# Processing BGP Peers
for peer in vif_data['dxvif']['bgpPeers']:
peer_info = {
peer['bgpPeerId']: {
'asn': peer['asn'],
'authKey': peer['authKey'],
'addressFamily': peer['addressFamily'],
'amazonAddress': peer['amazonAddress'],
'customerAddress': peer['customerAddress'],
'bgpPeerState': peer['bgpPeerState'],
'bgpStatus': peer['bgpStatus'],
# Include additional BGP peer information if necessary
}
}
vif_info['Peers'] = []
vif_info['Peers'].append(peer_info)
return vif_info
def format_dxgw_output(self, response):
# Extracting Direct Connect Gateway information
dxgw_info = {
'id': response['dxgw'].get('directConnectGatewayId'),
'name': response['dxgw'].get('directConnectGatewayName'),
'Amazon AS': response['dxgw'].get('amazonSideAsn'),
'vifs': [],
'tgw': {}
}
# Processing Virtual Interface (VIF) attachments
for attachment in response['attachments']:
vif_info = f"{attachment.get('virtualInterfaceId')} ({attachment.get('virtualInterfaceRegion')})"
dxgw_info['vifs'].append(vif_info)
# Processing Transit Gateway associations
for association in response['associations']:
tgw_id = association['associatedGateway'].get('id')
tgw_region = association['associatedGateway'].get('region')
allowed_prefixes = [prefix['cidr'] for prefix in association['allowedPrefixesToDirectConnectGateway']]
if tgw_id not in dxgw_info['tgw']:
dxgw_info['tgw'][tgw_id] = {
'region': tgw_region,
'cidrs': allowed_prefixes
}
else:
# Append CIDRs if the TGW ID is already in the dictionary
dxgw_info['tgw'][tgw_id]['cidrs'].extend(allowed_prefixes)
return dxgw_info
def format_rt_output(self, rt_info, filter_ip):
routes = rt_info.get('Routes', [])
most_specific_route = None
most_specific_length = -1 # Initial value for comparison
vpc_id = rt_info.get('VpcId') # Extract VPC ID from route table information
self.vpc_info = self.get_vpc_association_information(vpc_id)
for route in routes:
# Check direct destinations first
direct_destinations = []
if route.get('DestinationCidrBlock'):
direct_destinations.append(route['DestinationCidrBlock'])
if route.get('DestinationIpv6CidrBlock'):
direct_destinations.append(route['DestinationIpv6CidrBlock'])
# Check for the most specific match among direct destinations
for destination in direct_destinations:
try:
destination_network = ipaddress.ip_network(destination, strict=False)
if filter_ip:
filter_network = ipaddress.ip_network(filter_ip, strict=False)
if filter_network.version != destination_network.version:
continue
if filter_network.subnet_of(destination_network):
if destination_network.prefixlen >= most_specific_length:
most_specific_length = destination_network.prefixlen
most_specific_route = route
except ValueError:
continue
# If a direct route is already the most specific, skip prefix list check
if most_specific_route and route == most_specific_route:
continue
# Check prefix list destinations if no direct route is the most specific yet
if route.get('DestinationPrefixListId'):
prefix_list_id = route['DestinationPrefixListId']
prefix_list_cidrs = self.get_managed_prefix_list_entries(prefix_list_id)
for destination in prefix_list_cidrs:
try:
destination_network = ipaddress.ip_network(destination, strict=False)
if filter_ip:
if filter_network.version != destination_network.version:
continue
if filter_network.subnet_of(destination_network):
if destination_network.prefixlen > most_specific_length:
most_specific_length = destination_network.prefixlen
most_specific_route = route
except ValueError:
continue
output = {"vpcid": vpc_id}
# If no matching route is found, return an empty output or all routes if no filter is provided
if not filter_ip:
output["routes"] = [self.format_route(route) for route in routes]
elif not most_specific_route:
output["routes"] = []
else:
output["routes"] = [self.format_route(most_specific_route)]
return output
def format_tgw_route(self, route):
# Determine if it's a propagated or static route
route_type = 'p' if route.get('Type') == 'propagated' else 's'
# Get destination (supporting both IPv4 and IPv6)
destination = route.get('DestinationCidrBlock') or route.get('DestinationIpv6CidrBlock', '')
if route.get('State') == 'blackhole':
formatted_route = {f"({route_type}) {destination} via static": ["blackhole"]}
else:
# Collect and format the resource IDs
resource_ids = [attachment.get('ResourceId') for attachment in route.get('TransitGatewayAttachments', [])]
resource_type = next((attachment.get('ResourceType') for attachment in route.get('TransitGatewayAttachments', [])), 'unknown')
resource_count = len(resource_ids)
resource_ids_str = [', '.join(resource_ids)]
formatted_route = {f"({route_type}) {destination} via {resource_count} {resource_type}": resource_ids_str}
return formatted_route
def format_tgw_rt_output(self, tgw_rt_info, filter_ip=None):
routes = tgw_rt_info
most_specific_route = None
most_specific_length = -1 # Initial value for comparison
for route in routes:
# Extract destination (IPv4 or IPv6)
destination = route.get('DestinationCidrBlock') or route.get('DestinationIpv6CidrBlock', '')
try:
destination_network = ipaddress.ip_network(destination, strict=False)
if filter_ip:
filter_network = ipaddress.ip_network(filter_ip, strict=False)
if filter_network.version != destination_network.version:
continue
if filter_network.subnet_of(destination_network):
if destination_network.prefixlen > most_specific_length:
most_specific_length = destination_network.prefixlen
most_specific_route = route
except ValueError:
continue
output = {"tgw_routes": []}
# If no matching route is found, return all routes if no filter is provided
if not filter_ip:
output["tgw_routes"] = [self.format_tgw_route(route) for route in routes]
elif most_specific_route:
output["tgw_routes"] = [self.format_tgw_route(most_specific_route)]
return output
def format_sg_output(self, sg_info):
formatted_sg = {
"Description": sg_info.get("Description"),
"Group Name": sg_info.get("GroupName"),
"Inbound Rules": self.format_sg_rules(sg_info.get("IpPermissions", [])),
"Outbound Rules": self.format_sg_rules(sg_info.get("IpPermissionsEgress", []))
}
return formatted_sg
def format_sg_rules(self, rules):
formatted_rules = []
for rule in rules:
ip_protocol = rule.get("IpProtocol", "-1")
from_port = rule.get("FromPort", "-1")
to_port = rule.get("ToPort", "-1")
# Interpret '-1' as 'all'
ip_protocol = "all" if str(ip_protocol) == "-1" else ip_protocol
port_range = "all" if str(from_port) == "-1" else f"{from_port}-{to_port}" if from_port != to_port else f"{from_port}"
type = "type" if ip_protocol == "icmp" else "port"
# Handling different types of sources (CIDR, security group, etc.)
sources = []
for ip_range in rule.get("IpRanges", []):
sources.append([ip_range.get("CidrIp", ""), ip_range.get("Description", None)])
for ipv6_range in rule.get("Ipv6Ranges", []):
sources.append([ipv6_range.get("CidrIpv6", ""), ipv6_range.get("Description", None)])
for user_id_group_pair in rule.get("UserIdGroupPairs", []):
sources.append([user_id_group_pair.get("GroupId", ""), user_id_group_pair.get("Description", None)])
for prefix_list_id in rule.get("PrefixListIds", []):
sources.append([prefix_list_id.get("PrefixListId", ""), prefix_list_id.get("Description", None)])
# Formatting each rule
for source in sources:
if source[0].startswith("pl-"):
rule_str = {f"permit {ip_protocol} from: {source[0]} {type} {port_range} - Desc: {source[1]}": [', '.join(map(str, self.get_managed_prefix_list_entries(source[0])))]}
elif source[0].startswith("sg-"):
rule_str = {f"permit {ip_protocol} from: {source[0]} {type} {port_range} - Desc: {source[1]}": [', '.join(map(str, self.get_eni_by_sg(source[0])))]}
else:
rule_str = f"permit {ip_protocol} from: {source[0]} {type} {port_range} - Desc: {source[1]}"
formatted_rules.append(rule_str)
return formatted_rules
def format_acl_output(self, acl_info):
formatted_acl = {
"Network ACL ID": acl_info.get("NetworkAclId"),
"VPC ID": acl_info.get("VpcId"),
"Inbound": self.format_acl_entries(acl_info.get("Entries", []), egress=False),
"Outbound": self.format_acl_entries(acl_info.get("Entries", []), egress=True)
}
return formatted_acl
def format_acl_entries(self, entries, egress):
formatted_entries = []
for entry in entries:
if entry.get("Egress") == egress:
protocol = self.get_protocol_name(entry.get('Protocol'))
rule_action = "permit" if entry.get('RuleAction') == 'allow' else "deny"
cidr = entry.get('CidrBlock') or entry.get('Ipv6CidrBlock', '')
port_str = self.get_port_string(entry, protocol)
rule_str = f"{entry.get('RuleNumber')}: {rule_action} {protocol} from {cidr} {port_str}"
formatted_entries.append(rule_str)
return formatted_entries
def get_port_string(self, entry, protocol):
""" Format the port range for the ACL entry. """
if protocol in ['tcp', 'udp', '6', '17']: # TCP and UDP protocols
port_range = entry.get('PortRange')
if port_range:
return f"port: {port_range.get('From')}-{port_range.get('To')}"
return ""
def get_protocol_name(self, protocol_code):
""" Convert protocol code to a more understandable text. """
protocol_map = {
"-1": "all",
"1": "icmp",
"6": "tcp",
"17": "udp",
# Add other protocols as needed
}
return protocol_map.get(str(protocol_code), protocol_code)
def handle_eni_command(args, aws_fetcher, stdout = True):
current_time = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
if stdout:
print(f"{current_time}")
try:
eni_info = aws_fetcher.get_eni_information(args.identifier)
subnet_info = aws_fetcher.get_subnet_information(eni_info['SubnetId'])
formatted_output = aws_fetcher.format_eni_output(eni_info, subnet_info)
if stdout:
print(yaml.dump(formatted_output, sort_keys=False))
else:
return formatted_output
except Exception as e: