-
Notifications
You must be signed in to change notification settings - Fork 2
/
aws-cis-checker.py
1924 lines (1739 loc) · 89.2 KB
/
aws-cis-checker.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
# Based on https://github.com/awslabs/aws-security-benchmark/blob/672cacf5e8244d7b090ed6de613e91139b585dbd/aws_cis_foundation_framework/aws-cis-foundation-benchmark-checklist.py
# AWS CIS Benchmark v1.3.0
import csv
import time
import sys
import re
import getopt
from datetime import datetime
import boto3 # python3 -m pip install boto3
from botocore.exceptions import ClientError
from botocore.config import Config
from colorama import Fore, Style
import json
IAM_CLIENT = boto3.client('iam', config=Config(
connect_timeout=5, read_timeout=60, retries={'max_attempts': 20}))
S3_CLIENT = boto3.client('s3', config=Config(
connect_timeout=5, read_timeout=60, retries={'max_attempts': 20}))
PROGRESS = -1
TOTAL_CHECKS = 59
def banner():
print("""
(@@@@@@@@@@@. _____ __ __ _________
@@@/*************@@% / _ \/ \ / \/ _____/ ____ _____ ____
.@@@@@@@@@%%@#@@@@@@@@@@@#@#@@, / /_\ \ \/\/ /\_____ \ / _ \ / \_/ __ \
#@(***@@@#@%%@@////@@@@@#@#@@ / | \ / / ( <_> ) Y Y \ ___/
,@%**********@@/////(@****%@* \____|__ /\__/\ / /_______ /\____/|__|_| /\___ >
@@***********#@(////(@*****@@ \/ \/ \/ \/ \/
@@*************@@////@@*****@@ _________ .___ _________
*@@%**************&@&%@#******@@ \_ ___ \| |/ _____/
@@*@@****************@@*******@@ / \ \/| |\_____ \
@@****/@@**********************@@ \ \___| |/ \
,@@*********@@@%*****************@@. \______ /___/_______ /
@@@********************************@@ \/ \/
.@@/**********************************%@, _________ .__
.@&*************************************@@ \_ ___ \| |__ ____ ____ | | __ ___________
.@&***************************************@@ / \ \/| | \_/ __ \_/ ___\| |/ // __ \_ __ \
.@&*****************************************@@ \ \___| Y \ ___/\ \___| <\ ___/| | \/
.@&*******************************************@@ \______ /___| /\___ >\___ >__|_ \\___ >__|
\/ \/ \/ \/ \/ \/
v1.0
by Fiti@Secforce LTD
""")
return
def printProgressBar(iteration, total, prefix='Progress', suffix='Complete', decimals=1, length=50, fill='█', printEnd="\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 *
(iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print(f'\r{prefix} |{bar}| {percent}% {suffix}',
end=printEnd, file=sys.stderr)
# Print New Line on Complete
if iteration == total:
print()
def increment_progress():
global PROGRESS
global TOTAL_CHECKS
PROGRESS += 1
printProgressBar(PROGRESS, TOTAL_CHECKS)
def get_regions():
try:
client = boto3.client('ec2')
regions = [region['RegionName']
for region in client.describe_regions()['Regions']]
return regions
except ClientError as e:
print(Fore.RED + "EC2 Client error: " + str(e))
print(Style.RESET_ALL)
return False
def get_cred_report():
x = 0
status = ""
try:
while IAM_CLIENT.generate_credential_report()['State'] != "COMPLETE":
time.sleep(2)
x += 1
if x > 10:
status = "Fail: CredentialReport not available."
break
if "Fail" in status:
print(Fore.RED + "ERROR: " + status)
print(Style.RESET_ALL)
return False
response = IAM_CLIENT.get_credential_report()
report = []
reader = csv.DictReader(response['Content'].decode(
"utf-8").splitlines(), delimiter=',')
for row in reader:
report.append(row)
#print(json.dumps(report, indent=4, sort_keys=True))
return report
except ClientError as e:
print(Fore.RED + "IAM Client ERROR: " + str(e))
print(Style.RESET_ALL)
return False
def get_account_password_policy():
try:
response = IAM_CLIENT.get_account_password_policy()
return response['PasswordPolicy']
except ClientError as e:
if "cannot be found" in str(e):
print(
Fore.YELLOW + "[WARNING] IAM account password policy cannot be retrieved: " + str(e))
print(Style.RESET_ALL)
return False
def get_cloudtrails(regions):
trails = dict()
for n in regions:
try:
client = boto3.client('cloudtrail', region_name=n)
response = client.describe_trails()
temp = []
for m in response['trailList']:
if m['IsMultiRegionTrail'] is True:
if m['HomeRegion'] == n:
temp.append(m)
else:
temp.append(m)
if len(temp) > 0:
trails[n] = temp
except ClientError as e:
# Non-existent region
if "The security token included in the request is invalid" in str(e):
pass
return trails
def get_aws_info():
region_list = get_regions()
increment_progress()
cred_report = get_cred_report()
increment_progress()
password_policy = get_account_password_policy()
increment_progress()
cloudtrails = get_cloudtrails(region_list)
increment_progress()
return region_list, cred_report, password_policy, cloudtrails
# --- 1 Identity and Access Management ---
# 1.1 Maintain current contact details (Manual)
def control_1_1():
result = "Manual"
failReason = []
offenders = []
control = "1.1"
description = "Maintain current contact details."
failReason.append("Please, check contact details manually.")
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.2 Ensure security contact information is registered (Manual)
def control_1_2():
result = "Manual"
failReason = []
offenders = []
control = "1.2"
description = "Ensure security contact information is registered."
failReason.append("Please, check security contact details manually.")
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.3 Ensure security questions are registered in the AWS account (Manual)
def control_1_3():
result = "Manual"
failReason = []
offenders = []
control = "1.3"
description = "Ensure security questions are registered in the AWS account."
failReason.append("Please, check security questions manually.")
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.4 Ensure no root user account access key exists (Automated)
def control_1_4(credreport):
result = True
failReason = []
offenders = []
control = "1.4"
description = "Ensure no root account access key exists."
if "Fail" in credreport: # Report failure in control
result = "Manual"
failReason.append(
"Error retrieving credreport. Please check manually.")
else:
if (credreport[0]['access_key_1_active'] == "true") or (credreport[0]['access_key_2_active'] == "true"):
result = False
failReason.append("Root have active access keys")
client = boto3.client("sts")
offenders.append(
"Account ID " + str(client.get_caller_identity()["Account"]))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.5 Ensure MFA is enabled for the "root user" account (Automated)
def control_1_5():
result = True
failReason = []
offenders = []
control = "1.5"
description = "Ensure MFA is enabled for the root account"
response = IAM_CLIENT.get_account_summary()
if response['SummaryMap']['AccountMFAEnabled'] != 1:
result = False
failReason.append("Root account not using MFA")
client = boto3.client("sts")
offenders.append(
"Account ID " + str(client.get_caller_identity()["Account"]))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.6 Ensure hardware MFA is enabled for the "root user" account (Automated)
def control_1_6():
result = True
failReason = []
offenders = []
control = "1.6"
description = "Ensure hardware MFA is enabled for the \"root user\" account."
response = IAM_CLIENT.get_account_summary()
if response['SummaryMap']['AccountMFAEnabled'] == 1:
paginator = IAM_CLIENT.get_paginator('list_virtual_mfa_devices')
response_iterator = paginator.paginate(AssignmentStatus='Any',)
pagedResult = []
for page in response_iterator:
for n in page['VirtualMFADevices']:
pagedResult.append(n)
if "mfa/root-account-mfa-device" in str(pagedResult):
failReason.append("Root account not using hardware MFA")
result = False
client = boto3.client("sts")
offenders.append(
"Account ID " + str(client.get_caller_identity()["Account"]))
else:
result = False
failReason.append("Root account not using MFA")
client = boto3.client("sts")
offenders.append(
"Account ID " + str(client.get_caller_identity()["Account"]))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.7 Eliminate use of the root user for administrative and daily tasks (Automated)
def control_1_7(credreport):
result = True
failReason = []
offenders = []
control = "1.7"
description = "Eliminate use of the root user for administrative and daily tasks."
if "Fail" in credreport: # Report failure
result = "Manual"
failReason.append(
"Error retrieving credreport. Please check manually.")
else:
# Check if root is used in the last 24h
now = time.strftime('%Y-%m-%dT%H:%M:%S+00:00',
time.gmtime(time.time()))
frm = "%Y-%m-%dT%H:%M:%S+00:00"
try:
pwdDelta = (datetime.strptime(
now, frm) - datetime.strptime(credreport[0]['password_last_used'], frm))
if (pwdDelta.days == 0) & (pwdDelta.seconds > 0): # Used within last 24h
result = False
failReason.append("Root password used within 24h.")
except:
if credreport[0]['password_last_used'] == "N/A" or "no_information":
pass
else:
result = "Manual"
failReason.append("Something went wrong")
try:
key1Delta = (datetime.strptime(
now, frm) - datetime.strptime(credreport[0]['access_key_1_last_used_date'], frm))
if (key1Delta.days == 0) & (key1Delta.seconds > 0): # Used within last 24h
result = False
failReason.append("Root Key1 used within 24h.")
except:
if credreport[0]['access_key_1_last_used_date'] == "N/A" or "no_information":
pass
else:
result = "Manual"
failReason.append("Something went wrong")
try:
key2Delta = datetime.strptime(
now, frm) - datetime.strptime(credreport[0]['access_key_2_last_used_date'], frm)
if (key2Delta.days == 0) & (key2Delta.seconds > 0): # Used within last 24h
failReason.append("Root key2 used within 24h.")
result = False
except:
if credreport[0]['access_key_2_last_used_date'] == "N/A" or "no_information":
pass
else:
result = "Manual"
failReason.append("Something went wrong")
if result == False:
client = boto3.client("sts")
offenders.append(
"Account ID " + str(client.get_caller_identity()["Account"]))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.8 Ensure IAM password policy requires minimum length of 14 or greater (Automated)
def control_1_8(password_policy):
result = True
failReason = []
offenders = []
control = "1.8"
description = "Ensure IAM password policy requires minimum length of 14 or greater."
if password_policy is False:
result = False
failReason.append(
"Account is using default IAM password policy (weak).")
else:
if password_policy['MinimumPasswordLength'] < 14:
result = False
failReason.append(
"Password policy does not require at least 14 characters")
if result == False:
client = boto3.client("sts")
offenders.append(
"Account ID " + str(client.get_caller_identity()["Account"]))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.9 Ensure IAM password policy prevents password reuse (Automated)
def control_1_9(password_policy):
result = True
failReason = []
offenders = []
control = "1.9"
description = "Ensure IAM password policy prevents password reuse."
if password_policy is False:
result = False
failReason.append(
"Account is using default IAM password policy (weak).")
else:
try:
if password_policy['PasswordReusePrevention'] >= 24:
pass
else:
result = False
failReason.append(
"Password policy does not prevent reusing last 24 passwords")
except:
result = False
failReason.append(
"Password policy does not prevent reusing last 24 passwords")
if result == False:
client = boto3.client("sts")
offenders.append(
"Account ID " + str(client.get_caller_identity()["Account"]))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.10 Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password (Automated)
def control_1_10(credreport):
result = True
failReason = []
offenders = []
control = "1.10"
description = "Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password"
if "Fail" in credreport: # Report failure in control
result = "Manual"
failReason.append(
"Error retrieving credreport. Please check manually.")
else:
for user in credreport:
if user['password_enabled'] == "true":
if user['mfa_active'] == "false":
result = False
failReason.append("No MFA on user " + user['user'] + ".")
offenders.append(user['arn'])
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.11 Do not setup access keys during initial user setup for all IAM users that have a console password (Manual)
def control_1_11(): # Work in progress
result = True
failReason = []
offenders = []
control = "1.11"
description = "Do not setup access keys during initial user setup for all IAM users that have a console password."
result = "Manual"
failReason.append("Please, check this control manually.")
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.12 Ensure credentials unused for 90 days or greater are disabled (Automated)
def control_1_12(credreport):
result = True
failReason = []
offenders = []
control = "1.12"
description = "Ensure credentials unused for 90 days or greater are disabled"
if "Fail" in credreport: # Report failure
result = "Manual"
failReason.append(
"Error retrieving credreport. Please check manually.")
else:
now = time.strftime('%Y-%m-%dT%H:%M:%S+00:00',
time.gmtime(time.time()))
frm = "%Y-%m-%dT%H:%M:%S+00:00"
# Look for unused credentails
for user in credreport:
if user['password_enabled'] == "true":
try:
delta = datetime.strptime(
now, frm) - datetime.strptime(user['password_last_used'], frm)
# Verify password have been used in the last 90 days
if delta.days > 90:
result = False
failReason.append(
"Credentials unused > 90 days detected for user " + user['user'] + " (password).")
offenders.append(user['arn'] + ":password")
except:
pass # Never used
if user['access_key_1_active'] == "true":
try:
delta = datetime.strptime(
now, frm) - datetime.strptime(user['access_key_1_last_used_date'], frm)
# Verify password have been used in the last 90 days
if delta.days > 90:
result = False
failReason.append(
"Credentials unused > 90 days detected for user " + user['user'] + " (key1).")
offenders.append(user['arn'] + ":key1")
except:
pass
if user['access_key_2_active'] == "true":
try:
delta = datetime.strptime(
now, frm) - datetime.strptime(user['access_key_2_last_used_date'], frm)
# Verify password have been used in the last 90 days
if delta.days > 90:
result = False
failReason.append(
"Credentials unused > 90 days detected for user " + user['user'] + " (key2).")
offenders.append(user['arn'] + ":key2")
except:
# Never used
pass
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.13 Ensure there is only one active access key available for any single IAM user (Automated)
def control_1_13():
result = True
failReason = []
offenders = []
control = "1.13"
description = "Ensure there is only one active access key available for any single IAM user."
user_paginator = IAM_CLIENT.get_paginator('list_users')
for response in user_paginator.paginate():
for user in response['Users']:
key_paginator = IAM_CLIENT.get_paginator('list_access_keys')
for userkeys in key_paginator.paginate(UserName=user['UserName']):
if len(userkeys['AccessKeyMetadata']) > 1:
count = 0
for key in userkeys['AccessKeyMetadata']:
#print(key['UserName'] + ":" + key['AccessKeyId'] + ":" + key['Status'])
if key['Status'] == "Active":
count += 1
if count > 1:
result = False
failReason.append(
"User " + user['UserName'] + " has " + str(count) + " active keys.")
offenders.append(user['Arn'])
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.14 Ensure access keys are rotated every 90 days or less (Automated)
def control_1_14(credreport):
result = True
failReason = []
offenders = []
control = "1.14"
description = "Ensure access keys are rotated every 90 days or less."
if "Fail" in credreport: # Report failure in control
result = "Manual"
failReason.append(
"Error retrieving credreport. Please check manually.")
else:
now = time.strftime('%Y-%m-%dT%H:%M:%S+00:00',
time.gmtime(time.time()))
frm = "%Y-%m-%dT%H:%M:%S+00:00"
# Look for unused credentails
for user in credreport:
if user['access_key_1_active'] == "true":
try:
delta = datetime.strptime(
now, frm) - datetime.strptime(user['access_key_1_last_rotated'], frm)
# Verify keys have rotated in the last 90 days
if delta.days > 90:
result = False
failReason.append(
"Key1 rotation > 90 days for user " + user['user'])
offenders.append(user['arn'] + ":unrotated key1")
except:
pass
try:
last_used_datetime = datetime.strptime(
user['access_key_1_last_used_date'], frm)
last_rotated_datetime = datetime.strptime(
user['access_key_1_last_rotated'], frm)
# Verify keys have been used since rotation.
if last_used_datetime < last_rotated_datetime:
result = False
failReason.append(
"Key1 rotation not used since rotation for user" + user['user'])
offenders.append(user['arn'] + ":unused key1")
except:
pass
if user['access_key_2_active'] == "true":
try:
delta = datetime.strptime(
now, frm) - datetime.strptime(user['access_key_2_last_rotated'], frm)
# Verify keys have rotated in the last 90 days
if delta.days > 90:
result = False
failReason.append(
"Key2 rotation > 90 days for user" + user['user'])
offenders.append(user['arn'] + ":unrotated key2")
except:
pass
try:
last_used_datetime = datetime.strptime(
user['access_key_2_last_used_date'], frm)
last_rotated_datetime = datetime.strptime(
user['access_key_2_last_rotated'], frm)
# Verify keys have been used since rotation.
if last_used_datetime < last_rotated_datetime:
result = False
failReason.append(
"Key2 rotation not used since rotation for user" + user['user'])
offenders.append(user['arn'] + ":unused key2")
except:
pass
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.15 Ensure IAM Users Receive Permissions Only Through Groups (Automated)
def control_1_15():
result = True
failReason = []
offenders = []
control = "1.15"
description = "Ensure IAM Users Receive Permissions Only Through Groups"
paginator = IAM_CLIENT.get_paginator('list_users')
for response in paginator.paginate():
for user in response['Users']:
policies = IAM_CLIENT.list_attached_user_policies(
UserName=user['UserName'])
for policy in policies['AttachedPolicies']:
if policy['PolicyName'] != []:
result = False
failReason.append(
user['UserName'] + " IAM user have inline policies attached: " + str(policy['PolicyName']))
offenders.append(user['Arn'])
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.16 Ensure IAM policies that allow full "*:*" administrative privileges are not attached (Automated)
def control_1_16():
result = True
failReason = []
offenders = []
control = "1.16"
description = "Ensure IAM policies that allow full \"*:*\" administrative privileges are not created"
paginator = IAM_CLIENT.get_paginator('list_policies')
for response in paginator.paginate():
for policy in response['Policies']:
pol = IAM_CLIENT.get_policy_version(
PolicyArn=policy['Arn'], VersionId=policy['DefaultVersionId'])
# a policy may contain a single statement, a single statement in an array, or multiple statements in an array
if isinstance(pol['PolicyVersion']['Document']['Statement'], list):
for statement in pol['PolicyVersion']['Document']['Statement']:
try:
if statement['Effect'] == "Allow" and statement['Action'] == "*" and statement['Resource'] == "*":
result = False
failReason.append(
policy['Arn'] + " with full admin privileges")
offenders.append(policy['Arn'])
except Exception as e: # NotAction instead of Action, we don't care about these ones
pass
else:
statement = pol['PolicyVersion']['Document']['Statement']
try:
if statement['Effect'] == "Allow" and statement['Action'] == "*" and statement['Resource'] == "*":
result = False
failReason.append(
policy['Arn'] + " with full admin privileges")
offenders.append(policy['Arn'])
except Exception as e: # NotAction instead of Action, we don't care about these ones
pass
if len(offenders) == 1 and offenders[0] == "arn:aws:iam::aws:policy/AdministratorAccess":
result = "Manual"
failReason.append(
"AdministratorAccess is a default policy and not an issue by itself. Please verify which users have access to this policy to verify Risk.")
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.17 Ensure a support role has been created to manage incidents with AWS Support (Automated)
def control_1_17():
result = True
failReason = []
offenders = []
control = "1.17"
description = "Ensure a support role has been created to manage incidents with AWS Support"
try:
response = IAM_CLIENT.list_entities_for_policy(
PolicyArn='arn:aws:iam::aws:policy/AWSSupportAccess')
if response['PolicyGroups'] == [] and response['PolicyUsers'] == [] and response['PolicyRoles'] == []:
result = False
failReason.append(
"AWSSupportAccess attached to no user, group or role.")
except:
result = False
failReason.append("AWSSupportAccess policy not created")
if result == False:
client = boto3.client("sts")
offenders.append(
"Account ID " + str(client.get_caller_identity()["Account"]))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.18 Ensure IAM instance roles are used for AWS resource access from instances (Manual)
def control_1_18(region_list):
result = True
failReason = []
offenders = []
control = "1.18"
description = "Ensure IAM instance roles are used for AWS resource access from instances."
for region in region_list:
try:
client = boto3.client('ec2', region_name=region, config=Config(
connect_timeout=5, read_timeout=60, retries={'max_attempts': 20}))
response = client.describe_instances()
if bool(response['Reservations']):
for reservation in response['Reservations']:
for instance in reservation['Instances']:
try:
if instance['IamInstanceProfile']:
pass
except:
result = False
failReason.append(
"Region " + region + ", " + instance['InstanceId'] + " instance with no IAM role assigned for EC2")
offenders.append(
"Region " + region + ":Instance " + instance['InstanceId'])
except ClientError as e:
if e.response['Error']['Code'] == 'AuthFailure': # Non existing regions
pass
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.19 Ensure that all the expired SSL/TLS certificates stored in AWS IAM are removed (Automated)
def control_1_19():
result = True
failReason = []
offenders = []
control = "1.19"
description = "Ensure that all the expired SSL/TLS certificates stored in AWS IAM are removed."
now = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time()))
frm = "%Y-%m-%dT%H:%M:%SZ"
paginator = IAM_CLIENT.get_paginator('list_server_certificates')
for response in paginator.paginate():
if response['ServerCertificateMetadataList'] == []:
pass # No certificates
else:
for certificate in response['ServerCertificateMetadataList']:
delta = datetime.strptime(
now, frm) - datetime.strptime(certificate['Expiration'], frm)
if delta.days > 0: # Expired certificate
result = False
failReason.append(
"Certificate " + certificate['ServerCertificateName'] + "expired.")
offenders.append(certificate['Arn'])
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.20 Ensure that S3 Buckets are configured with 'Block public access (bucket settings)' (Automated)
def control_1_20():
result = True
failReason = []
offenders = []
control = "1.20"
description = "Ensure that S3 Buckets are configured with 'Block public access (bucket settings)'"
try:
response = S3_CLIENT.list_buckets()
for bucket in response['Buckets']:
try:
accessblock = S3_CLIENT.get_public_access_block(
Bucket=bucket['Name'])
if "false" in str(accessblock):
result = False
failReason.append(
bucket['Name'] + " bucket 'Block public access' misconfiguration.")
offenders.append("S3 Bucket:" + bucket['Name'])
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchPublicAccessBlockConfiguration':
result = False
failReason.append(
bucket['Name'] + " bucket 'Block public access' disabled.")
offenders.append("S3 Bucket:" + bucket['Name'])
except ClientError as e:
result = "Manual"
failReason.append("ERROR: " + str(e))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.21 Ensure that IAM Access analyzer is enabled (Automated)
def control_1_21(regions):
result = True
failReason = []
offenders = []
control = "1.21"
description = "Ensure that S3 Buckets are configured with 'Block public access (bucket settings)'Ensure that IAM Access analyzer is enabled."
for region in regions:
try:
client = boto3.client('accessanalyzer', region_name=region)
response = client.list_analyzers()
if response['analyzers'] == []:
result = False
failReason.append(
"No Access Analyzers for " + region + " region.")
else:
for analyzer in response['analyzers']:
if analyzer['status'] != "ACTIVE":
result = False
failReason.append(
analyzer['name'] + " status not 'ACTIVE'.")
except ClientError as e:
# Non-existent region
if "The security token included in the request is invalid" in str(e):
pass
else:
result = "Manual"
failReason.append("ERROR: " + str(e))
if result == False:
client = boto3.client("sts")
offenders.append(
"Account ID " + str(client.get_caller_identity()["Account"]))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 1.22 Ensure IAM users are managed centrally via identity federation or AWS Organizations for multi-account environments (Manual)
def control_1_22():
result = True
failReason = []
offenders = []
control = "1.22"
description = "Ensure IAM users are managed centrally via identity federation or AWS Organizations for multi-account environments."
result = "Manual"
failReason.append("Please, check security questions manually.")
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# --- 2. Storage ---
# 2.1 Simple Storage Service (S3)
# 2.1.1 Ensure all S3 buckets employ encryption-at-rest (Manual)
def control_2_1_1():
result = True
failReason = []
offenders = []
control = "2.1.1"
description = "Ensure all S3 buckets employ encryption-at-rest"
response = S3_CLIENT.list_buckets()
for bucket in response['Buckets']:
try:
enc = S3_CLIENT.get_bucket_encryption(Bucket=bucket['Name'])
rules = enc['ServerSideEncryptionConfiguration']['Rules']
for rule in rules:
if rule['ApplyServerSideEncryptionByDefault']['SSEAlgorithm'] != 'AES256' and rule['ApplyServerSideEncryptionByDefault']['SSEAlgorithm'] != 'aws:kms':
result = False
failReason.append(
"Wrong at-rest-encryption in " + bucket['Name'] + " bucket.")
offenders.append("S3 Bucket:" + bucket['Name'])
except ClientError as e:
if e.response['Error']['Code'] == 'ServerSideEncryptionConfigurationNotFoundError':
result = False
failReason.append("No at-rest-encryption in " +
bucket['Name'] + " bucket.")
offenders.append("S3 Bucket:" + bucket['Name'])
else:
print("Bucket: %s, unexpected error: %s" % (bucket['Name'], e))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 2.1.2 Ensure S3 Bucket Policy allows HTTPS requests (Manual)
def control_2_1_2():
result = True
failReason = []
offenders = []
control = "2.1.2"
description = "Ensure S3 Bucket Policy allows HTTPS requests"
response = S3_CLIENT.list_buckets()
for bucket in response['Buckets']:
try:
policy = S3_CLIENT.get_bucket_policy(Bucket=bucket['Name'])
safe_bucket = False
policy_json = json.loads(policy['Policy']) # Parsing policies
for statement in policy_json['Statement']:
if statement['Effect'] == "Deny" and statement['aws:SecureTransport'] == "false":
safe_bucket = True
if not safe_bucket:
result = False
failReason.append(
"Bucket " + bucket['Name'] + " allowing HTTP traffic.")
offenders.append("S3 Bucket:" + bucket['Name'])
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchBucketPolicy':
result = False
failReason.append(
"Bucket " + bucket['Name'] + " has no policy attached.")
offenders.append("S3 Bucket:" + bucket['Name'])
else:
print("Bucket: %s, unexpected error: %s" % (bucket['Name'], e))
except json.decoder.JSONDecodeError as e:
print("Unexpected JSON error: " + str(e))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 2.2 Elastic Compute Cloud (EC2)
# 2.2.1 Ensure EBS volume encryption is enabled (Manual)
def control_2_2_1(region_list):
result = True
failReason = []
offenders = []
control = "2.2.1"
description = "Ensure EBS volume encryption is enabled"
for region in region_list: # I think S3 buckets are not attached to a specific region. if so, add this loop
try:
ec2_client = boto3.client('ec2', region_name=region)
response = ec2_client.get_ebs_encryption_by_default()
if response['EbsEncryptionByDefault'] != "True":
result = False
failReason.append(
region + "EC2 region with EBS volume encryption disabled by default.")
offenders.append(region)
except ClientError as e:
if e.response['Error']['Code'] == 'AuthFailure': # Non existing regions
pass
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# --- 3. Logging ---
# 3.1 Ensure CloudTrail is enabled in all regions (Automated)
def control_3_1(cloudtrails):
result = False
failReason = []
offenders = []
control = "3.1"
description = "Ensure CloudTrail is enabled in all regions"
if bool(cloudtrails):
for cloudtrail in cloudtrails:
for trail in cloudtrails[cloudtrail]:
if trail['IsMultiRegionTrail']:
client = boto3.client('cloudtrail', region_name=cloudtrail)
response = client.get_trail_status(Name=trail['TrailARN'])
if response['IsLogging'] is True:
result = True
break
else:
failReason.append("No enabled multi region trails found")
offenders.append("Cloudtrails:NoMultiRegion")
else:
failReason.append("CloudTrails disabled in all regions")
offenders.append("Cloudtrails:AllRegions")
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 3.2 Ensure CloudTrail log file validation is enabled (Automated)
def control_3_2(cloudtrails):
result = True
failReason = []
offenders = []
control = "3.2"
description = "Ensure CloudTrail log file validation is enabled"
if bool(cloudtrails):
for cloudtrail in cloudtrails:
for trail in cloudtrails[cloudtrail]:
if trail['LogFileValidationEnabled'] == False:
result = False
failReason.append(
trail['TrailARN'] + " cloudtrail without log file validation enabled")
offenders.append(trail['TrailARN'])
else:
result = False
failReason.append("CloudTrails disabled in all regions")
offenders.append("Cloudtrails:AllRegions")
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 3.3 Ensure the S3 bucket used to store CloudTrail logs is not publicly accessible (Automated)
def control_3_3(cloudtrails):
result = True
failReason = []
offenders = []
control = "3.3"
description = "Ensure the S3 bucket CloudTrail logs to is not publicly accessible."
if bool(cloudtrails):
for cloudtrail in cloudtrails:
for trail in cloudtrails[cloudtrail]:
if "S3BucketName" in str(trail):
try:
response = S3_CLIENT.get_bucket_acl(
Bucket=trail['S3BucketName'])
for p in response['Grants']:
if re.search(r'(global/AllUsers|global/AuthenticatedUsers)', str(p['Grantee'])):
result = False
failReason.append(
trail['TrailARN'] + " publically accessible.")
offenders.append(
trail['TrailARN'] + ":PublicBucket")
except Exception as e:
result = "Manual"
if "AccessDenied" in str(e):
offenders.append(
trail['TrailARN'] + ":AccessDenied")
failReason.append(
"Missing permissions to verify bucket ACL in " + trail['TrailARN'])
elif "NoSuchBucket" in str(e):
offenders.append(trail['TrailARN'] + ":NoBucket")
failReason.append(
trail['TrailARN'] + " Trailbucket doesn't exist.")
else:
offenders.append(
trail['TrailARN'] + ":CannotVerify")
failReason.append(
"Cannot verify bucket ACL in " + trail['TrailARN'])
else:
result = False
offenders.append(trail['TrailARN'] + ":NoS3Logging")
failReason.append(
trail['TrailARN'] + " trail not configured to log to S3")
else:
result = False
failReason.append("CloudTrails disabled in all regions")
offenders.append("Cloudtrails:AllRegions")
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'Description': description, 'ControlId': control}
# 3.4 Ensure CloudTrail trails are integrated with CloudWatch Logs (Automated)
def control_3_4(cloudtrails):