-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws-cis-foundation-benchmark-checklist.py
2403 lines (2131 loc) · 102 KB
/
aws-cis-foundation-benchmark-checklist.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
"""Summary
Attributes:
AWS_CIS_BENCHMARK_VERSION (str): Description
CONFIG_RULE (bool): Description
CONTROL_1_1_DAYS (int): Description
IAM_CLIENT (TYPE): Description
REGIONS (list): Description
S3_WEB_REPORT (bool): Description
S3_WEB_REPORT_BUCKET (str): Description
S3_WEB_REPORT_EXPIRE (str): Description
S3_WEB_REPORT_OBFUSCATE_ACCOUNT (bool): Description
SCRIPT_OUTPUT_JSON (bool): Description
"""
from __future__ import print_function
import json
import csv
import time
import sys
import re
import tempfile
import getopt
import os
from datetime import datetime
import boto3
# --- Script controls ---
# CIS Benchmark version referenced. Only used in web report.
AWS_CIS_BENCHMARK_VERSION = "1.1"
# Would you like a HTML file generated with the result?
# This file will be delivered using a signed URL.
S3_WEB_REPORT = True
# Where should the report be delivered to?
# Make sure to update permissions for the Lambda role if you change bucket name.
S3_WEB_REPORT_BUCKET = "CHANGE_ME_TO_YOUR_S3_BUCKET"
# Create separate report files?
# This will add date and account number as prefix. Example: cis_report_111111111111_161220_1213.html
S3_WEB_REPORT_NAME_DETAILS = True
# How many hours should the report be available? Default = 168h/7days
S3_WEB_REPORT_EXPIRE = "168"
# Set to true if you wish to anonymize the account number in the report.
# This is mostly used for demo/sharing purposes.
S3_WEB_REPORT_OBFUSCATE_ACCOUNT = False
# Would you like to send the report signedURL to an SNS topic
SEND_REPORT_URL_TO_SNS = False
SNS_TOPIC_ARN = "CHANGE_ME_TO_YOUR_TOPIC_ARN"
# Would you like to print the results as JSON to output?
SCRIPT_OUTPUT_JSON = True
# Would you like to supress all output except JSON result?
# Can be used when you want to pipe result to another system.
# If using S3 reporting, please enable SNS integration to get S3 signed URL
OUTPUT_ONLY_JSON = False
# --- Control Parameters ---
# Control 1.18 - IAM manager and master role names <Not implemented yet, under review>
IAM_MASTER = "iam_master"
IAM_MANAGER = "iam_manager"
IAM_MASTER_POLICY = "iam_master_policy"
IAM_MANAGER_POLICY = "iam_manager_policy"
# Control 1.1 - Days allowed since use of root account.
CONTROL_1_1_DAYS = 0
# --- Global ---
IAM_CLIENT = boto3.client('iam')
S3_CLIENT = boto3.client('s3')
# --- 1 Identity and Access Management ---
# 1.1 Avoid the use of the "root" account (Scored)
def control_1_1_root_use(credreport):
"""Summary
Args:
credreport (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.1"
description = "Avoid the use of the root account"
scored = True
if "Fail" in credreport: # Report failure in control
sys.exit(credreport)
# 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 == CONTROL_1_1_DAYS) & (pwdDelta.seconds > 0): # Used within last 24h
failReason = "Used within 24h"
result = False
except:
if credreport[0]['password_last_used'] == "N/A" or "no_information":
pass
else:
print("Something went wrong")
try:
key1Delta = (datetime.strptime(now, frm) - datetime.strptime(credreport[0]['access_key_1_last_used_date'], frm))
if (key1Delta.days == CONTROL_1_1_DAYS) & (key1Delta.seconds > 0): # Used within last 24h
failReason = "Used within 24h"
result = False
except:
if credreport[0]['access_key_1_last_used_date'] == "N/A" or "no_information":
pass
else:
print("Something went wrong")
try:
key2Delta = datetime.strptime(now, frm) - datetime.strptime(credreport[0]['access_key_2_last_used_date'], frm)
if (key2Delta.days == CONTROL_1_1_DAYS) & (key2Delta.seconds > 0): # Used within last 24h
failReason = "Used within 24h"
result = False
except:
if credreport[0]['access_key_2_last_used_date'] == "N/A" or "no_information":
pass
else:
print("Something went wrong")
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.2 Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password (Scored)
def control_1_2_mfa_on_password_enabled_iam(credreport):
"""Summary
Args:
credreport (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.2"
description = "Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password"
scored = True
for i in range(len(credreport)):
# Verify if the user have a password configured
if credreport[i]['password_enabled'] == "true":
# Verify if password users have MFA assigned
if credreport[i]['mfa_active'] == "false":
result = False
failReason = "No MFA on users with password. "
offenders.append(str(credreport[i]['arn']))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.3 Ensure credentials unused for 90 days or greater are disabled (Scored)
def control_1_3_unused_credentials(credreport):
"""Summary
Args:
credreport (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.3"
description = "Ensure credentials unused for 90 days or greater are disabled"
scored = True
# Get current time
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 i in range(len(credreport)):
if credreport[i]['password_enabled'] == "true":
try:
delta = datetime.strptime(now, frm) - datetime.strptime(credreport[i]['password_last_used'], frm)
# Verify password have been used in the last 90 days
if delta.days > 90:
result = False
failReason = "Credentials unused > 90 days detected. "
offenders.append(str(credreport[i]['arn']) + ":password")
except:
pass # Never used
if credreport[i]['access_key_1_active'] == "true":
try:
delta = datetime.strptime(now, frm) - datetime.strptime(credreport[i]['access_key_1_last_used_date'], frm)
# Verify password have been used in the last 90 days
if delta.days > 90:
result = False
failReason = "Credentials unused > 90 days detected. "
offenders.append(str(credreport[i]['arn']) + ":key1")
except:
pass
if credreport[i]['access_key_2_active'] == "true":
try:
delta = datetime.strptime(now, frm) - datetime.strptime(credreport[i]['access_key_2_last_used_date'], frm)
# Verify password have been used in the last 90 days
if delta.days > 90:
result = False
failReason = "Credentials unused > 90 days detected. "
offenders.append(str(credreport[i]['arn']) + ":key2")
except:
# Never used
pass
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.4 Ensure access keys are rotated every 90 days or less (Scored)
def control_1_4_rotated_keys(credreport):
"""Summary
Args:
credreport (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.4"
description = "Ensure access keys are rotated every 90 days or less"
scored = True
# Get current time
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 i in range(len(credreport)):
if credreport[i]['access_key_1_active'] == "true":
try:
delta = datetime.strptime(now, frm) - datetime.strptime(credreport[i]['access_key_1_last_rotated'], frm)
# Verify keys have rotated in the last 90 days
if delta.days > 90:
result = False
failReason = "Key rotation >90 days or not used since rotation"
offenders.append(str(credreport[i]['arn']) + ":unrotated key1")
except:
pass
try:
last_used_datetime = datetime.strptime(credreport[i]['access_key_1_last_used_date'], frm)
last_rotated_datetime = datetime.strptime(credreport[i]['access_key_1_last_rotated'], frm)
# Verify keys have been used since rotation.
if last_used_datetime < last_rotated_datetime:
result = False
failReason = "Key rotation >90 days or not used since rotation"
offenders.append(str(credreport[i]['arn']) + ":unused key1")
except:
pass
if credreport[i]['access_key_2_active'] == "true":
try:
delta = datetime.strptime(now, frm) - datetime.strptime(credreport[i]['access_key_2_last_rotated'], frm)
# Verify keys have rotated in the last 90 days
if delta.days > 90:
result = False
failReason = "Key rotation >90 days or not used since rotation"
offenders.append(str(credreport[i]['arn']) + ":unrotated key2")
except:
pass
try:
last_used_datetime = datetime.strptime(credreport[i]['access_key_2_last_used_date'], frm)
last_rotated_datetime = datetime.strptime(credreport[i]['access_key_2_last_rotated'], frm)
# Verify keys have been used since rotation.
if last_used_datetime < last_rotated_datetime:
result = False
failReason = "Key rotation >90 days or not used since rotation"
offenders.append(str(credreport[i]['arn']) + ":unused key2")
except:
pass
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.5 Ensure IAM password policy requires at least one uppercase letter (Scored)
def control_1_5_password_policy_uppercase(passwordpolicy):
"""Summary
Args:
passwordpolicy (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.5"
description = "Ensure IAM password policy requires at least one uppercase letter"
scored = True
if passwordpolicy is False:
result = False
failReason = "Account does not have a IAM password policy."
else:
if passwordpolicy['RequireUppercaseCharacters'] is False:
result = False
failReason = "Password policy does not require at least one uppercase letter"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.6 Ensure IAM password policy requires at least one lowercase letter (Scored)
def control_1_6_password_policy_lowercase(passwordpolicy):
"""Summary
Args:
passwordpolicy (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.6"
description = "Ensure IAM password policy requires at least one lowercase letter"
scored = True
if passwordpolicy is False:
result = False
failReason = "Account does not have a IAM password policy."
else:
if passwordpolicy['RequireLowercaseCharacters'] is False:
result = False
failReason = "Password policy does not require at least one uppercase letter"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.7 Ensure IAM password policy requires at least one symbol (Scored)
def control_1_7_password_policy_symbol(passwordpolicy):
"""Summary
Args:
passwordpolicy (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.7"
description = "Ensure IAM password policy requires at least one symbol"
scored = True
if passwordpolicy is False:
result = False
failReason = "Account does not have a IAM password policy."
else:
if passwordpolicy['RequireSymbols'] is False:
result = False
failReason = "Password policy does not require at least one symbol"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.8 Ensure IAM password policy requires at least one number (Scored)
def control_1_8_password_policy_number(passwordpolicy):
"""Summary
Args:
passwordpolicy (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.8"
description = "Ensure IAM password policy requires at least one number"
scored = True
if passwordpolicy is False:
result = False
failReason = "Account does not have a IAM password policy."
else:
if passwordpolicy['RequireNumbers'] is False:
result = False
failReason = "Password policy does not require at least one number"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.9 Ensure IAM password policy requires minimum length of 14 or greater (Scored)
def control_1_9_password_policy_length(passwordpolicy):
"""Summary
Args:
passwordpolicy (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.9"
description = "Ensure IAM password policy requires minimum length of 14 or greater"
scored = True
if passwordpolicy is False:
result = False
failReason = "Account does not have a IAM password policy."
else:
if passwordpolicy['MinimumPasswordLength'] < 14:
result = False
failReason = "Password policy does not require at least 14 characters"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.10 Ensure IAM password policy prevents password reuse (Scored)
def control_1_10_password_policy_reuse(passwordpolicy):
"""Summary
Args:
passwordpolicy (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.10"
description = "Ensure IAM password policy prevents password reuse"
scored = True
if passwordpolicy is False:
result = False
failReason = "Account does not have a IAM password policy."
else:
try:
if passwordpolicy['PasswordReusePrevention'] == 24:
pass
else:
result = False
failReason = "Password policy does not prevent reusing last 24 passwords"
except:
result = False
failReason = "Password policy does not prevent reusing last 24 passwords"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.11 Ensure IAM password policy expires passwords within 90 days or less (Scored)
def control_1_11_password_policy_expire(passwordpolicy):
"""Summary
Args:
passwordpolicy (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.11"
description = "Ensure IAM password policy expires passwords within 90 days or less"
scored = True
if passwordpolicy is False:
result = False
failReason = "Account does not have a IAM password policy."
else:
if passwordpolicy['ExpirePasswords'] is True:
if 0 < passwordpolicy['MaxPasswordAge'] > 90:
result = False
failReason = "Password policy does not expire passwords after 90 days or less"
else:
result = False
failReason = "Password policy does not expire passwords after 90 days or less"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.12 Ensure no root account access key exists (Scored)
def control_1_12_root_key_exists(credreport):
"""Summary
Args:
credreport (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.12"
description = "Ensure no root account access key exists"
scored = True
if (credreport[0]['access_key_1_active'] == "true") or (credreport[0]['access_key_2_active'] == "true"):
result = False
failReason = "Root have active access keys"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.13 Ensure MFA is enabled for the "root" account (Scored)
def control_1_13_root_mfa_enabled():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.13"
description = "Ensure MFA is enabled for the root account"
scored = True
response = IAM_CLIENT.get_account_summary()
if response['SummaryMap']['AccountMFAEnabled'] != 1:
result = False
failReason = "Root account not using MFA"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.14 Ensure hardware MFA is enabled for the "root" account (Scored)
def control_1_14_root_hardware_mfa_enabled():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.14"
description = "Ensure hardware MFA is enabled for the root account"
scored = True
# First verify that root is using MFA (avoiding false positive)
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 = "Root account not using hardware MFA"
result = False
else:
result = False
failReason = "Root account not using MFA"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.15 Ensure security questions are registered in the AWS account (Not Scored/Manual)
def control_1_15_security_questions_registered():
"""Summary
Returns:
TYPE: Description
"""
result = "Manual"
failReason = ""
offenders = []
control = "1.15"
description = "Ensure security questions are registered in the AWS account, please verify manually"
scored = False
failReason = "Control not implemented using API, please verify manually"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.16 Ensure IAM policies are attached only to groups or roles (Scored)
def control_1_16_no_policies_on_iam_users():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.16"
description = "Ensure IAM policies are attached only to groups or roles"
scored = True
paginator = IAM_CLIENT.get_paginator('list_users')
response_iterator = paginator.paginate()
pagedResult = []
for page in response_iterator:
for n in page['Users']:
pagedResult.append(n)
offenders = []
for n in pagedResult:
policies = IAM_CLIENT.list_user_policies(
UserName=n['UserName'],
MaxItems=1
)
if policies['PolicyNames'] != []:
result = False
failReason = "IAM user have inline policy attached"
offenders.append(str(n['Arn']))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.17 Enable detailed billing (Scored)
def control_1_17_detailed_billing_enabled():
"""Summary
Returns:
TYPE: Description
"""
result = "Manual"
failReason = ""
offenders = []
control = "1.17"
description = "Enable detailed billing, please verify manually"
scored = True
failReason = "Control not implemented using API, please verify manually"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.18 Ensure IAM Master and IAM Manager roles are active (Scored)
def control_1_18_ensure_iam_master_and_manager_roles():
"""Summary
Returns:
TYPE: Description
"""
result = "True"
failReason = "No IAM Master or IAM Manager role created"
offenders = []
control = "1.18"
description = "Ensure IAM Master and IAM Manager roles are active. Control under review/investigation"
scored = True
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.19 Maintain current contact details (Scored)
def control_1_19_maintain_current_contact_details():
"""Summary
Returns:
TYPE: Description
"""
result = "Manual"
failReason = ""
offenders = []
control = "1.19"
description = "Maintain current contact details, please verify manually"
scored = True
failReason = "Control not implemented using API, please verify manually"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.20 Ensure security contact information is registered (Scored)
def control_1_20_ensure_security_contact_details():
"""Summary
Returns:
TYPE: Description
"""
result = "Manual"
failReason = ""
offenders = []
control = "1.20"
description = "Ensure security contact information is registered, please verify manually"
scored = True
failReason = "Control not implemented using API, please verify manually"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.21 Ensure IAM instance roles are used for AWS resource access from instances (Scored)
def control_1_21_ensure_iam_instance_roles_used():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.21"
description = "Ensure IAM instance roles are used for AWS resource access from instances, application code is not audited"
scored = True
failReason = "Instance not assigned IAM role for EC2"
client = boto3.client('ec2')
response = client.describe_instances()
offenders = []
for n, _ in enumerate(response['Reservations']):
try:
if response['Reservations'][n]['Instances'][0]['IamInstanceProfile']:
pass
except:
result = False
offenders.append(str(response['Reservations'][n]['Instances'][0]['InstanceId']))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.22 Ensure a support role has been created to manage incidents with AWS Support (Scored)
def control_1_22_ensure_incident_management_roles():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.22"
description = "Ensure a support role has been created to manage incidents with AWS Support"
scored = True
offenders = []
try:
response = IAM_CLIENT.list_entities_for_policy(
PolicyArn='arn:aws:iam::aws:policy/AWSSupportAccess'
)
if (len(response['PolicyGroups']) + len(response['PolicyUsers']) + len(response['PolicyRoles'])) == 0:
result = False
failReason = "No user, group or role assigned AWSSupportAccess"
except:
result = False
failReason = "AWSSupportAccess policy not created"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.23 Do not setup access keys during initial user setup for all IAM users that have a console password (Not Scored)
def control_1_23_no_active_initial_access_keys_with_iam_user(credreport):
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.23"
description = "Do not setup access keys during initial user setup for all IAM users that have a console password"
scored = False
offenders = []
for n, _ in enumerate(credreport):
if (credreport[n]['access_key_1_active'] or credreport[n]['access_key_2_active'] == 'true') and n > 0:
response = IAM_CLIENT.list_access_keys(
UserName=str(credreport[n]['user'])
)
for m in response['AccessKeyMetadata']:
if re.sub(r"\s", "T", str(m['CreateDate'])) == credreport[n]['user_creation_time']:
result = False
failReason = "Users with keys created at user creation time found"
offenders.append(str(credreport[n]['arn']) + ":" + str(m['AccessKeyId']))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 1.24 Ensure IAM policies that allow full "*:*" administrative privileges are not created (Scored)
def control_1_24_no_overly_permissive_policies():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "1.24"
description = "Ensure IAM policies that allow full administrative privileges are not created"
scored = True
offenders = []
paginator = IAM_CLIENT.get_paginator('list_policies')
response_iterator = paginator.paginate(
Scope='Local',
OnlyAttached=False,
)
pagedResult = []
for page in response_iterator:
for n in page['Policies']:
pagedResult.append(n)
for m in pagedResult:
policy = IAM_CLIENT.get_policy_version(
PolicyArn=m['Arn'],
VersionId=m['DefaultVersionId']
)
statements = []
# a policy may contain a single statement, a single statement in an array, or multiple statements in an array
if isinstance(policy['PolicyVersion']['Document']['Statement'], list):
for statement in policy['PolicyVersion']['Document']['Statement']:
statements.append(statement)
else:
statements.append(policy['PolicyVersion']['Document']['Statement'])
for n in statements:
# a policy statement has to contain either an Action or a NotAction
if 'Action' in n.keys() and n['Effect'] == 'Allow':
if ("'*'" in str(n['Action']) or str(n['Action']) == "*") and ("'*'" in str(n['Resource']) or str(n['Resource']) == "*"):
result = False
failReason = "Found full administrative policy"
offenders.append(str(m['Arn']))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# --- 2 Logging ---
# 2.1 Ensure CloudTrail is enabled in all regions (Scored)
def control_2_1_ensure_cloud_trail_all_regions(cloudtrails):
"""Summary
Args:
cloudtrails (TYPE): Description
Returns:
TYPE: Description
"""
result = False
failReason = ""
offenders = []
control = "2.1"
description = "Ensure CloudTrail is enabled in all regions"
scored = True
for m, n in cloudtrails.iteritems():
for o in n:
if o['IsMultiRegionTrail']:
client = boto3.client('cloudtrail', region_name=m)
response = client.get_trail_status(
Name=o['TrailARN']
)
if response['IsLogging'] is True:
result = True
break
if result is False:
failReason = "No enabled multi region trails found"
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 2.2 Ensure CloudTrail log file validation is enabled (Scored)
def control_2_2_ensure_cloudtrail_validation(cloudtrails):
"""Summary
Args:
cloudtrails (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "2.2"
description = "Ensure CloudTrail log file validation is enabled"
scored = True
for m, n in cloudtrails.iteritems():
for o in n:
if o['LogFileValidationEnabled'] is False:
result = False
failReason = "CloudTrails without log file validation discovered"
offenders.append(str(o['TrailARN']))
offenders = set(offenders)
offenders = list(offenders)
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 2.3 Ensure the S3 bucket CloudTrail logs to is not publicly accessible (Scored)
def control_2_3_ensure_cloudtrail_bucket_not_public(cloudtrails):
"""Summary
Args:
cloudtrails (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "2.3"
description = "Ensure the S3 bucket CloudTrail logs to is not publicly accessible"
scored = True
for m, n in cloudtrails.iteritems():
for o in n:
# We only want to check cases where there is a bucket
if "S3BucketName" in str(o):
try:
response = S3_CLIENT.get_bucket_acl(Bucket=o['S3BucketName'])
for p in response['Grants']:
# print("Grantee is " + str(p['Grantee']))
if re.search(r'(global/AllUsers|global/AuthenticatedUsers)', str(p['Grantee'])):
result = False
offenders.append(str(o['TrailARN']) + ":PublicBucket")
if "Publically" not in failReason:
failReason = failReason + "Publically accessible CloudTrail bucket discovered."
except Exception as e:
result = False
if "AccessDenied" in str(e):
offenders.append(str(o['TrailARN']) + ":AccessDenied")
if "Missing" not in failReason:
failReason = "Missing permissions to verify bucket ACL. " + failReason
elif "NoSuchBucket" in str(e):
offenders.append(str(o['TrailARN']) + ":NoBucket")
if "Trailbucket" not in failReason:
failReason = "Trailbucket doesn't exist. " + failReason
else:
offenders.append(str(o['TrailARN']) + ":CannotVerify")
if "Cannot" not in failReason:
failReason = "Cannot verify bucket ACL. " + failReason
else:
result = False
offenders.append(str(o['TrailARN']) + "NoS3Logging")
failReason = "Cloudtrail not configured to log to S3. " + failReason
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 2.4 Ensure CloudTrail trails are integrated with CloudWatch Logs (Scored)
def control_2_4_ensure_cloudtrail_cloudwatch_logs_integration(cloudtrails):
"""Summary
Args:
cloudtrails (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "2.4"
description = "Ensure CloudTrail trails are integrated with CloudWatch Logs"
scored = True
for m, n in cloudtrails.iteritems():
for o in n:
try:
if "arn:aws:logs" in o['CloudWatchLogsLogGroupArn']:
pass
else:
result = False
failReason = "CloudTrails without CloudWatch Logs discovered"
offenders.append(str(o['TrailARN']))
except:
result = False
failReason = "CloudTrails without CloudWatch Logs discovered"
offenders.append(str(o['TrailARN']))
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# 2.5 Ensure AWS Config is enabled in all regions (Scored)
def control_2_5_ensure_config_all_regions(regions):
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "2.5"
description = "Ensure AWS Config is enabled in all regions"
scored = True
globalConfigCapture = False # Only one region needs to capture global events
for n in regions:
configClient = boto3.client('config', region_name=n)
response = configClient.describe_configuration_recorder_status()
# Get recording status
try:
if not response['ConfigurationRecordersStatus'][0]['recording'] is True:
result = False
failReason = "Config not enabled in all regions, not capturing all/global events or delivery channel errors"
offenders.append(str(n) + ":NotRecording")
except:
result = False
failReason = "Config not enabled in all regions, not capturing all/global events or delivery channel errors"
offenders.append(str(n) + ":NotRecording")
# Verify that each region is capturing all events
response = configClient.describe_configuration_recorders()
try:
if not response['ConfigurationRecorders'][0]['recordingGroup']['allSupported'] is True:
result = False
failReason = "Config not enabled in all regions, not capturing all/global events or delivery channel errors"
offenders.append(str(n) + ":NotAllEvents")
except:
pass # This indicates that Config is disabled in the region and will be captured above.
# Check if region is capturing global events. Fail is verified later since only one region needs to capture them.
try:
if response['ConfigurationRecorders'][0]['recordingGroup']['includeGlobalResourceTypes'] is True:
globalConfigCapture = True
except:
pass
# Verify the delivery channels
response = configClient.describe_delivery_channel_status()
try:
if response['DeliveryChannelsStatus'][0]['configHistoryDeliveryInfo']['lastStatus'] != "SUCCESS":
result = False
failReason = "Config not enabled in all regions, not capturing all/global events or delivery channel errors"
offenders.append(str(n) + ":S3orSNSDelivery")
except:
pass # Will be captured by earlier rule
try:
if response['DeliveryChannelsStatus'][0]['configStreamDeliveryInfo']['lastStatus'] != "SUCCESS":
result = False
failReason = "Config not enabled in all regions, not capturing all/global events or delivery channel errors"
offenders.append(str(n) + ":SNSDelivery")