forked from paulbayer/Inventory_Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInventory_Modules.py
More file actions
1705 lines (1544 loc) · 62.8 KB
/
Inventory_Modules.py
File metadata and controls
1705 lines (1544 loc) · 62.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
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
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
def get_regions(fkey, fprofile="default"):
import boto3, logging
session_ec2=boto3.Session(profile_name=fprofile)
region_info=session_ec2.client('ec2')
regions=region_info.describe_regions()
RegionNames=[]
for x in range(len(regions['Regions'])):
RegionNames.append(regions['Regions'][x]['RegionName'])
if "all" in fkey or "ALL" in fkey:
return(RegionNames)
RegionNames2=[]
for x in fkey:
for y in RegionNames:
logging.info('Have %s | Looking for %s', y, x)
if y.find(x) >=0:
logging.info('Found %s', y)
RegionNames2.append(y)
return(RegionNames2)
def get_ec2_regions(fkey, fprofile="default"):
import boto3, logging
session_ec2=boto3.Session(profile_name=fprofile)
region_info=session_ec2.client('ec2')
regions=region_info.describe_regions(
Filters=[{
'Name': 'opt-in-status',
'Values': ['opt-in-not-required', 'opted-in']
}]
)
RegionNames=[]
for x in range(len(regions['Regions'])):
RegionNames.append(regions['Regions'][x]['RegionName'])
if "all" in fkey or "ALL" in fkey:
return(RegionNames)
RegionNames2=[]
for x in fkey:
for y in RegionNames:
logging.info('Have %s | Looking for %s', y, x)
if y.find(x) >=0:
logging.info('Found %s', y)
RegionNames2.append(y)
return(RegionNames2)
def get_service_regions(service, fkey):
"""
Parameters:
service=the AWS service we're trying to get regions for. This is useful since not all services are supported in all regions.
fkey=A string fragment of what region we're looking for. If 'all', then we send back all regions for that service. If they send "us-" (for example), we would send back only those regions which matched that fragment. This is good for focusing a search on only those regions you're searching within.
"""
import boto3, logging
s=boto3.Session()
regions=s.get_available_regions(service, partition_name='aws', allow_non_regional=False)
if "all" in fkey or "ALL" in fkey:
return(regions)
RegionNames=[]
for x in fkey:
for y in regions:
logging.info('Have %s | Looking for %s', y, x)
if y.find(x) >=0:
logging.info('Found %s', y)
RegionNames.append(y)
return(RegionNames)
def get_profiles(fSkipProfiles=None, fprofiles=None):
'''
We assume that the user of this function wants all profiles.
If they provide a list of profile strings (in fprofiles), then we compare those strings to the full list of profiles we have, and return those profiles that contain the strings they sent.
'''
import boto3
import logging
if fSkipProfiles==None:
fSkipProfiles=['default']
if fprofiles==None:
fprofiles=['all']
my_Session=boto3.Session()
my_profiles=my_Session._session.available_profiles
if "all" in fprofiles or "ALL" in fprofiles:
return(my_profiles)
ProfileList=[]
for x in fprofiles:
for y in my_profiles:
logging.info('Have %s| Looking for %s', y, x)
if y.find(x) >= 0:
logging.info('Found profile %s', y)
ProfileList.append(y)
return(ProfileList)
def get_profiles2(fSkipProfiles=None, fprofiles=None):
'''
We assume that the user of this function wants all profiles.
If they provide a list of profile strings (in fprofiles), then we compare those strings to the full list of profiles we have, and return those profiles that contain the strings they sent.
'''
import boto3
if fSkipProfiles==None:
fSkipProfiles=['default']
if fprofiles==None:
fprofiles=['all']
my_Session=boto3.Session()
my_profiles=my_Session._session.available_profiles
if "all" in fprofiles or "ALL" in fprofiles:
my_profiles=list(set(my_profiles)-set(fSkipProfiles))
else:
my_profiles=list(set(fprofiles)-set(fSkipProfiles))
return(my_profiles)
def get_parent_profiles(fprofiles=None, fSkipProfiles=None):
'''
This function should only return profiles from Master Payer Accounts.
If they provide a list of profile strings (in fprofiles), then we compare those
strings to the full list of profiles we have, and return those profiles that
contain the strings AND are Master Payer Accounts.
'''
import boto3, logging
from botocore.exceptions import ClientError
ERASE_LINE='\x1b[2K'
if fSkipProfiles==None:
fSkipProfiles=['default']
if fprofiles==None:
fprofiles=['all']
my_Session=boto3.Session()
my_profiles=my_Session._session.available_profiles
logging.info("Profile string sent: %s", fprofiles)
if "all" in fprofiles or "ALL" in fprofiles or "All" in fprofiles:
my_profiles=list(set(my_profiles)-set(fSkipProfiles))
logging.info("my_profiles %s:", my_profiles)
else:
my_profiles=list(set(fprofiles)-set(fSkipProfiles))
my_profiles2=[]
NumOfProfiles=len(my_profiles)
for profile in my_profiles:
print(ERASE_LINE, "Checking {} Profile - {} more profiles to go".format(profile, NumOfProfiles), end='\r')
logging.warning("Finding whether %s is a root profile", profile)
try:
AcctResult=find_if_org_root(profile)
except ClientError as my_Error:
print(my_Error)
continue
NumOfProfiles-=1
if AcctResult in ['Root', 'StandAlone']:
logging.warning("%s is a %s Profile", profile, AcctResult)
my_profiles2.append(profile)
else:
logging.warning("%s is a %s Profile", profile, AcctResult)
return(my_profiles2)
def find_if_org_root(fProfile):
import logging
logging.info("Finding if %s is an ORG root", fProfile)
org_acct_number=find_org_attr(fProfile)
logging.info("Profile %s's Org Account Number is %s", fProfile, org_acct_number['MasterAccountId'])
acct_number=find_account_number(fProfile)
if org_acct_number['MasterAccountId']==acct_number:
logging.info("%s is a Root account", fProfile)
return('Root')
elif org_acct_number['MasterAccountId']=='StandAlone':
logging.info("%s is a Standalone account", fProfile)
return('StandAlone')
else:
logging.info("%s is a Child account", fProfile)
return('Child')
def find_if_alz(fProfile):
import boto3
session_org=boto3.Session(profile_name=fProfile)
client_org=session_org.client('s3')
bucket_list=client_org.list_buckets()
response={}
response['BucketName'] = None
response['ALZ'] = False
for bucket in bucket_list['Buckets']:
if "aws-landing-zone-configuration" in bucket['Name']:
response['BucketName'] = bucket['Name']
response['ALZ'] = True
response['Region'] = find_bucket_location(fProfile,bucket['Name'])
return(response)
def find_bucket_location(fProfile, fBucketname):
import boto3
import logging
from botocore.exceptions import ClientError
session_org=boto3.Session(profile_name=fProfile)
client_org=session_org.client('s3')
try:
response=client_org.get_bucket_location(
Bucket=fBucketname
)
except ClientError as my_Error:
if str(my_Error).find("AccessDenied") > 0:
logging.error("Authorization Failure for profile {}".format(fProfile))
return(None)
if response['LocationConstraint'] is None:
location='us-east-1'
else:
location=response['LocationConstraint']
return(location)
def find_acct_email(fOrgRootProfile, fAccountId):
import boto3
"""
This function *unfortunately* only works with organization accounts.
"""
session_org=boto3.Session(profile_name=fOrgRootProfile)
client_org=session_org.client('organizations')
email_addr=client_org.describe_account(AccountId=fAccountId)['Account']['Email']
# email_addr=response['Account']['Email']
return (email_addr)
def find_account_number(fProfile):
import boto3, logging
from botocore.exceptions import ClientError, CredentialRetrievalError, InvalidConfigError
response='123456789012'
try:
session_sts=boto3.Session(profile_name=fProfile)
logging.info("Looking for profile %s", fProfile)
client_sts=session_sts.client('sts')
response=client_sts.get_caller_identity()['Account']
except ClientError as my_Error:
if str(my_Error).find("UnrecognizedClientException") > 0:
print("{}: Security Issue".format(fProfile))
elif str(my_Error).find("InvalidClientTokenId") > 0:
print("{}: Security Token is bad - probably a bad entry in config".format(fProfile))
pass
except CredentialRetrievalError as my_Error:
if str(my_Error).find("CredentialRetrievalError") > 0:
print("{}: Some custom process isn't working".format(fProfile))
pass
except InvalidConfigError as my_Error:
if str(my_Error).find("InvalidConfigError") > 0:
print("{}: profile is invalid. Probably due to a config profile based on a credential that doesn't work".format(fProfile))
pass
except:
print("Other kind of failure for profile {}".format(fProfile))
# print(my_Error)
pass
return(response)
def find_calling_identity(fProfile):
import boto3, logging
from botocore.exceptions import ClientError
try:
session_sts=boto3.Session(profile_name=fProfile)
logging.info("Getting creds used within profile %s", fProfile)
client_sts=session_sts.client('sts')
response=client_sts.get_caller_identity()
creds={}
creds['Arn']=response['Arn']
creds['AccountId']=response['Account']
creds['Short']=response['Arn'][response['Arn'].rfind(':')+1:]
except ClientError as my_Error:
if str(my_Error).find("UnrecognizedClientException") > 0:
print("{}: Security Issue".format(fProfile))
elif str(my_Error).find("InvalidClientTokenId") > 0:
print("{}: Security Token is bad - probably a bad entry in config".format(fProfile))
else:
print("Other kind of failure for profile {}".format(fProfile))
print(my_Error)
creds="Failure"
return (creds)
def find_org_attr(fProfile):
import boto3, logging
from botocore.exceptions import ClientError, CredentialRetrievalError
"""
Response is a dict that looks like this:
{
'Id': 'o-zzzzzzzzzz',
'Arn': 'arn:aws:organizations::123456789012:organization/o-zzzzzzzzzz',
'FeatureSet': 'ALL',
'MasterAccountArn': 'arn:aws:organizations::123456789012:account/o-zzzzzzzzzz/123456789012',
'MasterAccountId': '123456789012',
'MasterAccountEmail': 'xxxxx@yyyy.com',
'AvailablePolicyTypes': [
{
'Type': 'SERVICE_CONTROL_POLICY',
'Status': 'ENABLED'
}
]
}
"""
try:
Success = False
FailResponse = {'MasterAccountId': 'StandAlone', 'Id': 'None'}
session_org=boto3.Session(profile_name=fProfile)
client_org=session_org.client('organizations')
response=client_org.describe_organization()['Organization']
Success=True
except ClientError as my_Error:
if str(my_Error).find("UnrecognizedClientException") > 0:
print(fProfile+": Security Issue")
elif str(my_Error).find("AWSOrganizationsNotInUseException") > 0:
logging.warning("%s: Account isn't a part of an Organization", fProfile) # Stand-alone account
# Need to figure out how to provide the account's own number here as MasterAccountId
elif str(my_Error).find("InvalidClientTokenId") > 0:
print(fProfile+": Security Token is bad - probably a bad entry in config")
pass
except CredentialRetrievalError as my_Error:
print("{}: Failure pulling or updating credentials".format(fProfile))
print(my_Error)
pass
except:
print("Other kind of failure")
pass
if Success:
return (response)
else:
return (FailResponse)
def find_org_attr2(fProfile):
import boto3
# Unused... and renamed
session_org=boto3.Session(profile_name=fProfile)
client_org=session_org.client('organizations')
response=client_org.describe_organization()
root_org=response['Organization']['MasterAccountId']
org_id=response['Organization']['Id']
return (root_org, org_id)
def find_child_accounts2(fProfile):
"""
This is an example of the list response from this call:
[{'ParentProfile':'LZRoot', 'AccountId': 'xxxxxxxxxxxx', 'AccountEmail': 'EmailAddr1@example.com'},
{'ParentProfile':'LZRoot', 'AccountId': 'yyyyyyyyyyyy', 'AccountEmail': 'EmailAddr2@example.com'},
{'ParentProfile':'LZRoot', 'AccountId': 'zzzzzzzzzzzz', 'AccountEmail': 'EmailAddr3@example.com'}]
This can be convenient for appending and removing.
"""
import boto3, logging
from botocore.exceptions import ClientError
# Renamed since I'm using the one below instead.
child_accounts=[]
session_org=boto3.Session(profile_name=fProfile)
client_org=session_org.client('organizations')
try:
response=client_org.list_accounts()
except ClientError as my_Error:
logging.warning("Profile %s doesn't represent an Org Root account", fProfile)
return()
theresmore=True
while theresmore:
for account in response['Accounts']:
logging.warning("Profile: %s | Account ID: %s | Account Email: %s" % (fProfile, account['Id'], account['Email']))
child_accounts.append({
'ParentProfile': fProfile,
'AccountId': account['Id'],
'AccountEmail': account['Email'],
'AccountStatus': account['Status']
})
if 'NextToken' in response:
theresmore=True
response=client_org.list_accounts(NextToken=response['NextToken'])
else:
theresmore=False
return (child_accounts)
def find_child_accounts(fProfile="default"):
"""
This call returns a dictionary response, unlike the "find_child_accounts2" function (above) which returns a list.
Our dictionary call looks like this:
{'xxxxxxxxxxxx': 'EmailAddr1@example.com',
'yyyyyyyyyyyy': 'EmailAddr2@example.com',
'zzzzzzzzzzzz': 'EmailAddr3@example.com'}
This is convenient because it is easily sortable.
"""
import boto3, logging
from botocore.exceptions import ClientError
child_accounts={}
session_org=boto3.Session(profile_name=fProfile)
theresmore=False
try:
client_org=session_org.client('organizations')
response=client_org.list_accounts()
theresmore=True
except ClientError as my_Error:
logging.warning("Profile %s doesn't represent an Org Root account", fProfile)
return()
while theresmore:
for account in response['Accounts']:
# Create a key/value pair with the AccountID:AccountEmail
child_accounts[account['Id']]=account['Email']
if 'NextToken' in response:
theresmore=True
response=client_org.list_accounts(NextToken=response['NextToken'])
else:
theresmore=False
return (child_accounts)
def RemoveCoreAccounts(MainList, AccountsToRemove=None):
import logging
"""
MainList is expected to come through looking like this:
[{'AccountEmail': 'User+LZ@example.com', 'AccountId': '0123xxxx8912'},
{'AccountEmail': 'User+LZ_Log@example.com', 'AccountId': '1234xxxx9012'},
< ... >
{'AccountEmail': 'User+LZ_SS@example.com', 'AccountId': '9876xxxx1000'},
{'AccountEmail': 'User+Demo@example.com', 'AccountId': '9638xxxx012'}]
AccountsToRemove is simply a list of accounts you don't want to screw with. It might look like this:
['9876xxxx1000', '9638xxxx1012']
"""
if AccountsToRemove == None:
AccountsToRemove = []
NewCA=[]
for i in range(len(MainList)):
if MainList[i]['AccountId'] in AccountsToRemove:
logging.info("Comparing %s to above", str(MainList[i]['AccountId']))
continue
else:
logging.info("Account %s was allowed", str(MainList[i]['AccountId']))
NewCA.append(MainList[i])
return(NewCA)
# def get_child_access(fRootProfile, fRegion, fChildAccount, fRoleList=None):
# """
# - fRootProfile is a string
# - rRegion expects a string representing one of the AWS regions ('us-east-1', 'eu-west-1', etc.)
# - fChildAccount expects an AWS account number (ostensibly of a Child Account)
# - fRoleList expects a list of roles to try, but defaults to a list of typical roles, in case you don't provide
#
# The response object is a Session object within boto3
# """
# import boto3, logging
# from botocore.exceptions import ClientError
#
# if fRoleList == None:
# fRoleList = ['AWSCloudFormationStackSetExecutionRole', 'AWSControlTowerExecution', 'OrganizationAccountAccessRole',
# 'DevAccess']
# sts_session=boto3.Session(profile_name=fRootProfile)
# sts_client=sts_session.client('sts', region_name=fRegion)
# for role in fRoleList:
# try:
# role_arn='arn:aws:iam::'+fChildAccount+':role/'+role
# account_credentials=sts_client.assume_role(
# RoleArn=role_arn,
# RoleSessionName="Find-ChildAccount-Things")['Credentials']
# session_aws=boto3.Session(
# aws_access_key_id=account_credentials['AccessKeyId'],
# aws_secret_access_key=account_credentials['SecretAccessKey'],
# aws_session_token=account_credentials['SessionToken'],
# region_name=fRegion)
# return(session_aws)
# except ClientError as my_Error:
# if my_Error.response['Error']['Code'] == 'ClientError':
# logging.info(my_Error)
# return_string="{} failed. Try Again".format(str(fRoleList))
# continue
# return(return_string)
def get_child_access2(fRootProfile, fChildAccount, fRegion='us-east-1', fRoleList=None):
"""
- fRootProfile is a string
- fChildAccount expects an AWS account number (ostensibly of a Child Account)
- rRegion expects a string representing one of the AWS regions ('us-east-1', 'eu-west-1', etc.)
- fRoleList expects a list of roles to try, but defaults to a list of typical roles, in case you don't provide
The first response object is a dict with account_credentials to pass onto other functions
The second response object is the rolename that worked to gain access to the target account
"""
import boto3
import logging
from botocore.exceptions import ClientError
if fRoleList == None:
fRoleList = ['AWSCloudFormationStackSetExecutionRole', 'AWSControlTowerExecution', 'OrganizationAccountAccessRole',
'AdministratorAccess', 'Owner']
if not isinstance(fChildAccount, str): # Make sure the passed in account number is a string
fChildAccount=str(fChildAccount)
sts_session=boto3.Session(profile_name=fRootProfile)
sts_client=sts_session.client('sts', region_name=fRegion)
account_credentials = {'Profile': fRootProfile,
'AccessKeyId': None,
'SecretAccessKey': None,
'SessionToken': None,
'AccountNumber': None}
for role in fRoleList:
try:
logging.info("Trying to access account %s using %s profile assuming role: %s", fChildAccount, fRootProfile, role)
role_arn='arn:aws:iam::'+fChildAccount+':role/'+role
account_credentials=sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName="Find-ChildAccount-Things")['Credentials']
return(account_credentials, role)
except ClientError as my_Error:
if my_Error.response['Error']['Code'] == 'ClientError':
logging.info(my_Error)
return_string="{} failed. Try Again".format(str(fRoleList))
continue
# Returns a dict object since that's what's expected
# It will only get to the part below if the child isn't accessed properly using the roles already defined
return(account_credentials, return_string)
def find_if_Isengard_registered(ocredentials):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
"""
import boto3, logging
logging.warning("Key ID #: %s ", str(ocredentials['AccessKeyId']))
session_iam=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken']
)
iam_info=session_iam.client('iam')
roles=iam_info.list_roles()['Roles']
for y in range(len(roles)):
if roles[y]['RoleName']=='IsengardRole-DO-NOT-DELETE':
return(True)
return(False)
def enable_drift_on_stacks(ocredentials, fRegion, fStackName):
import boto3, logging
session_cfn=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_cfn=session_cfn.client('cloudformation')
logging.warning("Enabling drift detection on Stack %s in Account %s in region %s", fStackName, ocredentials['AccountNumber'], fRegion)
response=client_cfn.detect_stack_drift(
StackName=fStackName
)
"""
Above - Generic functions
Below - Specific functions to specific features
"""
def find_sns_topics(ocredentials, fRegion, fTopicFrag=None):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
Returns:
List of Topic ARNs found that match the fragment sent
"""
import boto3
import logging
if fTopicFrag == None:
fTopicFrag = ['all']
session_sns=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_sns=session_sns.client('sns')
#TODO: Enable pagination
response=client_sns.list_topics()
TopicList=[]
for item in response['Topics']:
TopicList.append(item['TopicArn'])
if 'all' in fTopicFrag:
logging.warning("Looking for all SNS Topics in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
logging.info("Topic Arns Returned: %s", TopicList)
logging.warning("We found %s SNS Topics", len(TopicList))
return(TopicList)
else:
logging.warning("Looking for specific SNS Topics in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
TopicList2=[]
for item in fTopicFrag:
for Topic in TopicList:
logging.info('Have %s | Looking for %s', Topic, item)
if Topic.find(item) >=0:
logging.error('Found %s', Topic)
TopicList2.append(Topic)
logging.warning("We found %s SNS Topics", len(TopicList2))
return(TopicList2)
def find_role_names(ocredentials, fRegion, fRoleNameFrag=None):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
Returns:
List of Role Names found that match the fragment list sent
"""
import boto3
import logging
if fRoleNameFrag==None:
fRoleNameFrag=['all']
session_iam=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_iam=session_iam.client('iam')
#TODO: Enable pagination
response=client_iam.list_roles()['Roles']
RoleNameList=[]
for item in response:
RoleNameList.append(item['RoleName'])
if 'all' in fRoleNameFrag:
logging.warning("Looking for all RoleNames in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
logging.info("RoleName Arns Returned: %s", RoleNameList)
logging.warning("We found %s RoleNames", len(RoleNameList))
return(RoleNameList)
else:
logging.warning("Looking for specific RoleNames in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
RoleNameList2=[]
for item in fRoleNameFrag:
for RoleName in RoleNameList:
logging.info('Have %s | Looking for %s', RoleName, item)
if RoleName.find(item) >=0:
logging.error('Found %s', RoleName)
RoleNameList2.append(RoleName)
logging.warning("We found %s Roles", len(RoleNameList2))
return(RoleNameList2)
def find_cw_log_group_names(ocredentials, fRegion, fCWLogGroupFrag=None):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
Returns:
List of CloudWatch Log Group Names found that match the fragment list
"""
import boto3
import logging
if fCWLogGroupFrag==None:
fCWLogGroupFrag=['all']
session_cw=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_cw=session_cw.client('logs')
# TODO: Enable pagination # Defaults to 50
CWLogGroupList=[]
FirstTime=True
response={}
while 'nextToken' in response.keys() or FirstTime:
FirstTime=False
response = client_cw.describe_log_groups()
for item in response['logGroups']:
CWLogGroupList.append(item['logGroupName'])
if 'all' in fCWLogGroupFrag:
logging.warning("Looking for all Log Group names in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
logging.info("Log Group Names Returned: %s", CWLogGroupList)
logging.warning("We found %s Log Group names", len(CWLogGroupList))
return(CWLogGroupList)
else:
logging.warning("Looking for specific Log Group names in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
CWLogGroupList2=[]
for item in fCWLogGroupFrag:
for logGroupName in CWLogGroupList:
logging.info('Have %s | Looking for %s', logGroupName, item)
if logGroupName.find(item) >=0:
logging.error('Found %s', logGroupName)
CWLogGroupList2.append(logGroupName)
logging.warning("We found %s Log Groups", len(CWLogGroupList2))
return(CWLogGroupList2)
def find_account_vpcs(ocredentials, fRegion, defaultOnly=False):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
"""
import boto3
import logging
session_vpc=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_vpc=session_vpc.client('ec2')
if defaultOnly:
logging.warning("Looking for default VPCs in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
logging.info("defaultOnly: %s", str(defaultOnly))
response=client_vpc.describe_vpcs(
Filters=[
{
'Name': 'isDefault',
'Values': ['true']
} ]
)
else:
logging.warning("Looking for all VPCs in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
logging.info("defaultOnly: %s", str(defaultOnly))
response=client_vpc.describe_vpcs()
#TODO: Enable pagination
logging.warning("We found %s VPCs", len(response['Vpcs']))
return(response)
def find_config_recorders(ocredentials, fRegion):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
Returned object looks like:
{
"ConfigurationRecorders": [
{
"name": "AWS-Landing-Zone-BaselineConfigRecorder",
"roleARN": "arn:aws:iam::123456789012:role/AWS-Landing-Zone-ConfigRecorderRole",
"recordingGroup": {
"allSupported": true,
"includeGlobalResourceTypes": true,
"resourceTypes": []
}
}
]
}
Pagination isn't an issue here since only one config recorder per account / region is allowed.
"""
import boto3
import logging
session_cfg=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_cfg=session_cfg.client('config')
logging.warning("Looking for Config Recorders in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
response=client_cfg.describe_configuration_recorders()
# logging.info(response)
return(response)
def del_config_recorder(ocredentials, fRegion, fConfig_recorder_name):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
fRegion=region
fConfig_recorder_name=Config Recorder Name
"""
import boto3
import logging
session_cfg=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_cfg=session_cfg.client('config')
logging.error("Deleting Config Recorder %s from Region %s in account %s", fConfig_recorder_name, fRegion, ocredentials['AccountNumber'])
response=client_cfg.delete_configuration_recorder(ConfigurationRecorderName=fConfig_recorder_name)
return(response) # There is no response to send back
def find_delivery_channels(ocredentials, fRegion):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
Returned object looks like:
{
'DeliveryChannels': [
{
'name': 'string',
's3BucketName': 'string',
's3KeyPrefix': 'string',
'snsTopicARN': 'string',
'configSnapshotDeliveryProperties': {
'deliveryFrequency': 'One_Hour'|'Three_Hours'|'Six_Hours'|'Twelve_Hours'|'TwentyFour_Hours'
}
},
]
}
Pagination isn't an issue here since delivery channels are limited to only one / account / region
"""
import boto3, logging
session_cfg=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_cfg=session_cfg.client('config')
logging.warning("Looking for Delivery Channels in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
response=client_cfg.describe_delivery_channels()
return(response)
def del_delivery_channel(ocredentials, fRegion, fDelivery_channel_name):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
rRegion=region
fDelivery_channel_name=delivery channel name
"""
import boto3, logging
session_cfg=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_cfg=session_cfg.client('config')
logging.error("Deleting Delivery Channel %s from Region %s in account %s", fDelivery_channel_name, fRegion, ocredentials['AccountNumber'])
response=client_cfg.delete_delivery_channels(DeliveryChannelName=fDelivery_channel_name)
return(response)
def find_cloudtrails(ocredentials, fRegion, fCloudTrailnames=None):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
fRegion=region
fCloudTrailnames=List of CloudTrail names we're looking for (null value returns all cloud trails)
Returned Object looks like this:
{
'trailList': [
{
'Name': 'string',
'S3BucketName': 'string',
'S3KeyPrefix': 'string',
'SnsTopicName': 'string',
'SnsTopicARN': 'string',
'IncludeGlobalServiceEvents': True|False,
'IsMultiRegionTrail': True|False,
'HomeRegion': 'string',
'TrailARN': 'string',
'LogFileValidationEnabled': True|False,
'CloudWatchLogsLogGroupArn': 'string',
'CloudWatchLogsRoleArn': 'string',
'KmsKeyId': 'string',
'HasCustomEventSelectors': True|False,
'HasInsightSelectors': True|False,
'IsOrganizationTrail': True|False
},
]
}
"""
import boto3, logging
from botocore.exceptions import ClientError
session_ct=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_ct=session_ct.client('cloudtrail')
logging.info("Looking for CloudTrail trails in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
if fCloudTrailnames == None: # Therefore - they're really looking for a list of trails
try:
response=client_ct.list_trails()
trailname = "Various"
fullresponse = response['Trails']
if 'NextToken' in response.keys():
while 'NextToken' in response.keys():
response=client_ct.list_trails()
for i in range(len(response['Trails'])):
fullresponse.append(response['Trails'][i])
except ClientError as my_Error:
if str(my_Error).find("InvalidTrailNameException") > 0:
logging.error("Bad CloudTrail name provided")
fullresponse=trailname+" didn't work. Try Again"
return(fullresponse, trailname)
else:
# TODO: This doesn't work... Needs to be fixed.
# They've provided a list of trails and want specific info about them
for trailname in fCloudTrailnames:
try:
response=client_ct.describe_trails(trailNameList=[trailname])
if len(response['trailList']) > 0:
return(response, trailname)
except ClientError as my_Error:
if str(my_Error).find("InvalidTrailNameException") > 0:
logging.error("Bad CloudTrail name provided")
response=trailname+" didn't work. Try Again"
return(response, trailname)
def del_cloudtrails(ocredentials, fRegion, fCloudTrail):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
fRegion=region
fCloudTrail=CloudTrail we're deleting
"""
import boto3, logging
session_ct=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_ct=session_ct.client('cloudtrail')
logging.info("Deleting CloudTrail %s in account %s from Region %s", fCloudTrail, ocredentials['AccountNumber'], fRegion)
response=client_ct.delete_trail(Name=fCloudTrail)
return(response)
def find_gd_invites(ocredentials, fRegion):
"""
ocredentials is an object with the following structure:
- ['AccessKeyId'] holds the AWS_ACCESS_KEY
- ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY
- ['SessionToken'] holds the AWS_SESSION_TOKEN
- ['AccountNumber'] holds the account number
fRegion=region
"""
import boto3, logging
from botocore.exceptions import ClientError
session_gd=boto3.Session(
aws_access_key_id=ocredentials['AccessKeyId'],
aws_secret_access_key=ocredentials['SecretAccessKey'],
aws_session_token=ocredentials['SessionToken'],
region_name=fRegion)
client_gd=session_gd.client('guardduty')
logging.info("Looking for GuardDuty invitations in account %s from Region %s", ocredentials['AccountNumber'], fRegion)
try:
response=client_gd.list_invitations()
except ClientError as my_Error:
if str(my_Error).find("AuthFailure") > 0:
print(ocredentials['AccountNumber']+": Authorization Failure for account {}".format(ocredentials['AccountNumber']))
if str(my_Error).find("security token included in the request is invalid") > 0:
print("Account #:"+ocredentials['AccountNumber']+" - It's likely that the region you're trying ({}) isn\'t enabled for your account".format(fRegion))
else:
print(my_Error)
response={'Invitations': []}
return(response)
def delete_gd_invites(ocredentials, fRegion, fAccountId):
"""