This repository has been archived by the owner on Feb 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathaws_compliance.py
executable file
·796 lines (689 loc) · 26.7 KB
/
aws_compliance.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
#!/usr/bin/env python
import argparse
from datetime import datetime
import csv
import json
import os
import sys
import time
FALSE_VALUES = ['f', 'false', 'none']
ACCOUNTS_WITHOUT_EC2_APP_INSTANCES = [
'govuk-pay-dev',
'govuk-pay-ci',
'govuk-pay-test',
'govuk-pay-staging',
'govuk-pay-prod',
'govuk-pay-deploy',
]
app_description = """
Run AWS compliance reports
Environment variables looked at:
ONLY_SHOW_FAILED
REGION
S3_BUCKETS_TO_SKIP
SEND_REPORT_TO_SNS
SNS_TOPIC_ARN
UNIX_ACCOUNT_REPORT_BUCKET
VULS_REPORT_BUCKET
"""
parser = argparse.ArgumentParser(description=app_description)
parser.add_argument(
'-e', '--echo',
action='store_true',
help='Echoes the args and then exits'
)
parser.add_argument(
'--only-failed',
default=str(os.getenv('ONLY_SHOW_FAILED')).lower() not in FALSE_VALUES,
type=bool,
help='only show failed'
)
env_region = os.getenv('REGION')
env_region = env_region or os.getenv('AWS_REGION')
env_region = env_region or os.getenv('AWS_DEFAULT_REGION')
env_region = env_region or 'eu-west-1'
parser.add_argument(
'--region',
type=str,
default=env_region,
help='AWS region; defaults to environment variable or eu-west-1'
)
parser.add_argument(
'--skip-buckets',
type=str,
nargs='*',
default=[
s
for s in ((os.getenv('S3_BUCKETS_TO_SKIP') or '').split(','))
if len(s)
],
help='list of strs; buckets to skip'
)
parser.add_argument(
'--send-report-to-sns',
type=bool,
default=str(os.getenv('SEND_REPORT_TO_SNS')).lower() not in FALSE_VALUES,
help='bool; send the report to SNS; default false'
)
parser.add_argument(
'--sns-topic-arn',
type=str,
default=os.getenv('SNS_TOPIC_ARN') or '',
help='sns topic to send report to; default blank'
)
unix_default_bucket = 'pay-govuk-unix-accounts-dev'
parser.add_argument(
'--unix-acc-report-bucket',
type=str,
default=os.getenv('UNIX_ACCOUNT_REPORT_BUCKET') or unix_default_bucket,
help='bucket where unix account reports are stored; default {b}'.format(
b=unix_default_bucket
)
)
parser.add_argument('--vuls-high-threshold', type=float, default=7,
help='vuls high threshold; default 7')
parser.add_argument('--vuls-medium-threshold', type=float, default=4.5,
help='vuls medium threshold; default 4.5')
parser.add_argument('--vuls-low-threshold', type=float, default=0,
help='vuls low threshold; default 0')
parser.add_argument(
'--vuls-ignore-unscored',
type=bool,
default=str(os.getenv('VULS_IGNORE_UNSCORED_CVE') or True) == 'true',
help='ignore unscored cves; default true'
)
vuls_min_sev_opts = ['unknown', 'low', 'medium', 'high']
vuls_min_sev_help_text = """
minimum alert severity; default medium; unknown / low / medium / high
"""
parser.add_argument(
'--vuls-min-alert-severity',
type=str,
default='medium',
choices=vuls_min_sev_opts,
help=vuls_min_sev_help_text
)
vuls_bucket = os.getenv('VULS_REPORT_BUCKET') or 'pay-govuk-pay-vuls'
parser.add_argument(
'--vuls-report-bucket',
type=str,
default=vuls_bucket,
help='bucket where vuls reports are stored; default {b}'.format(
b='pay-govuk-pay-vuls'
)
)
args = parser.parse_args()
if args.echo:
for arg_name, arg_val in vars(args).items():
if arg_name == 'echo':
continue
print('{n} : {v}'.format(n=arg_name.rjust(24), v=str(arg_val)))
exit(0)
# This should come after the argument parsing.
# This is so you know your command is validated before being asked for MFA.
import botocore
import boto3
EC2_CLIENT = boto3.client('ec2', region_name=args.region)
IAM_CLIENT = boto3.client('iam', region_name=args.region)
S3_CLIENT = boto3.client('s3', region_name=args.region)
# S3 versioning enabled on all buckets
def s3_versioning_enabled():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "s3_versioning_enabled"
description = "Ensure S3 versioning is enabled on all buckets"
scored = False
for bucket in S3_CLIENT.list_buckets()['Buckets']:
if should_skip_bucket(bucket):
continue
try:
versioning = S3_CLIENT.get_bucket_versioning(Bucket=bucket['Name'])
except:
result = False
failReason = "Buckets found without versioning enabled"
offenders.append(bucket['Name'])
try:
versioning_status = versioning['Status']
if (versioning_status == 'Enabled'):
pass
except:
result = False
failReason = "Buckets found without versioning enabled"
offenders.append(bucket['Name'])
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# S3 logging enabled on all buckets
def s3_logging_enabled():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "s3_logging_enabled"
description = "Ensure S3 logging is enabled on all buckets"
scored = False
for bucket in S3_CLIENT.list_buckets()['Buckets']:
if should_skip_bucket(bucket):
continue
try:
logging = S3_CLIENT.get_bucket_logging(Bucket=bucket['Name'])
except:
result = False
failReason = "Buckets found without logging enabled"
offenders.append(bucket['Name'])
try:
if logging['LoggingEnabled']:
pass
except:
result = False
failReason = "Buckets found without logging enabled"
offenders.append(bucket['Name'])
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
# Reboots required
def reboots_required():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "reboots_required"
description = "Instances requiring a reboot, see /var/log/pay-reboots-required.log on instances. See guidance https://pay-team-manual.cloudapps.digital/manual/support/pay-aws-compliance.html#instances-requiring-a-reboot"
scored = False
filters = [{'Name':'tag:reboots_required', 'Values':['true']}]
reservations = EC2_CLIENT.describe_instances(Filters=filters).get('Reservations', [])
if reservations:
result = False
failReason = 'Instances found requiring reboots'
for instance in reservations:
instance_name = instance['Instances'][0]['InstanceId']
for tags in instance['Instances'][0]['Tags']:
if tags["Key"] == 'Name':
instance_name = tags["Value"]
offenders.append(instance_name)
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
def root_account_use(credreport):
"""Summary
Args:
credreport (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "root_account_use"
description = "Root account has been logged into - avoid the use of the root account"
scored = False
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 == 0) & (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 == 0) & (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 == 0) & (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}
# Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password
def mfa_on_password_enabled_iam(credreport):
"""Summary
Args:
credreport (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "mfa_on_password_enabled_iam"
description = "Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password"
scored = False
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}
# Ensure credentials unused for 90 days or greater are disabled
def unused_credentials(credreport):
"""Summary
Args:
credreport (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "unused_credentials"
description = "Ensure credentials unused for 90 days or greater are disabled"
scored = False
# 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(f'{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(f'{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(f'{str(credreport[i]["arn"])}:key2')
except:
# Never used
pass
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
def old_api_keys(credreport):
"""Summary
Args:
credreport (TYPE): Description
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "old_api_keys"
description = "Ensure API keys older than 90 days are rotated."
scored = False
# Get current time
now = time.strftime('%Y-%m-%dT%H:%M:%S+00:00', time.gmtime(time.time()))
format = "%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, format) - datetime.strptime(credreport[i]['access_key_1_last_rotated'], format)
# Verify password have been used in the last 90 days
if delta.days > 90:
result = False
failReason = "API key older than 90 days detected."
offenders.append(f'{str(credreport[i]["arn"])}:key1')
except:
pass
if credreport[i]['access_key_2_active'] == "true":
try:
delta = datetime.strptime(now, format) - datetime.strptime(credreport[i]['access_key_2_last_rotated'], format)
# Verify password have been used in the last 90 days
if delta.days > 90:
result = False
failReason = "API key older than 90 days detected."
offenders.append(f'{str(credreport[i]["arn"])}:key2')
except:
# Never used
pass
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
def should_skip_bucket(bucket):
if args.skip_buckets:
if bucket['Name'] in args.skip_buckets:
return True
# Unix account last login reports
def unix_account_last_login_reports():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
control = "unix_account_last_login_reports"
description = "Unix account last login older than 90 days"
scored = False
unused_unix_accounts_by_instance = {}
today = time.strftime('%Y-%m-%d', time.gmtime(time.time()))
try:
response = S3_CLIENT.list_objects(Bucket=args.unix_acc_report_bucket,Prefix=today)
if 'Contents' in response:
for object in response['Contents']:
report = S3_CLIENT.get_object(Bucket=args.unix_acc_report_bucket,Key=object['Key'])
unused_accounts_json = json.loads(report['Body'].read())
instance = object['Key'].split('__')[0].split('/')[2]
unused_unix_accounts_by_instance.setdefault(instance, [])
for account in unused_accounts_json:
if account not in unused_unix_accounts_by_instance[instance]:
unused_unix_accounts_by_instance[instance].append(account)
# filter instances less than 90 days
for instance in list(unused_unix_accounts_by_instance):
if instance not in instances_in_scope(list(unused_unix_accounts_by_instance)):
del unused_unix_accounts_by_instance[instance]
if len(list(unused_unix_accounts_by_instance)) > 0:
result = False
failReason = "Unix accounts found with last login over 90 days ago"
else:
result = False
failReason = "No Unix user account reports found for today in " + args.unix_acc_report_bucket
except botocore.exceptions.ClientError as error:
result = False
failReason = "An error occurred whilst querying the unix user report. " + error.response['Error']['Message']
return {'Result': result, 'failReason': failReason, 'Offenders': unused_unix_accounts_by_instance, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
def instances_in_scope(instances):
instances_in_scope = []
filters = [
{'Name':'tag:Name', 'Values':instances},
{'Name':'instance-state-name','Values':['running']}
]
reservations = EC2_CLIENT.describe_instances(Filters=filters).get('Reservations', [])
for reservation in reservations:
for instance in reservation['Instances']:
if launch_time_delta(instance['LaunchTime']) > 90:
for tags in instance['Tags']:
if tags["Key"] == 'Name':
instances_in_scope.append(tags["Value"])
return instances_in_scope
def launch_time_delta(launch_time):
frm = "%Y-%m-%d %H:%M:%S+00:00"
now = time.strftime(frm, time.gmtime(time.time()))
delta = datetime.strptime(now, frm) - datetime.strptime(str(launch_time), frm)
return delta.days
# Vuls reports
def vuls_reports():
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
control = "vuls_reports"
description = "Vuls reports"
scored = False
cve_summary = dict()
response = dict()
try:
today = time.strftime('%Y-%m-%d', time.gmtime(time.time()))
response = S3_CLIENT.list_objects(Bucket=args.vuls_report_bucket,Prefix=today)
except Exception as e:
result = False
if "AccessDenied" in str(e):
offenders.append(str(args.vuls_report_bucket) + ":AccessDenied")
if "Missing" not in failReason:
failReason = "Missing permissions to " + args.vuls_report_bucket + failReason
elif "NoSuchBucket" in str(e):
offenders.append(str(args.vuls_report_bucket) + ":NoBucket")
if "exist" not in failReason:
failReason = "Bucket doesn't exist. " + args.vuls_report_bucket + failReason
else:
offenders.append(str(args.vuls_report_bucket) + ":Error listing objects")
failReason = "Error listing objects: " + str(e)
if 'Contents' in response:
for object in response['Contents']:
if object['Key'].split('.')[-1] == "json":
report = S3_CLIENT.get_object(Bucket=args.vuls_report_bucket,Key=object['Key'])
report_body = json.loads(report['Body'].read())
known_cves = report_body.get('KnownCves')
unknown_cves = report_body.get('UnknownCves')
if report_body.get('Optional'):
options = dict(report_body['Optional'])
if options.get('environment'):
env = options.get('environment')
if env not in offenders:
offenders.append(env)
if known_cves:
for known_cve in known_cves:
gen_cve_summary(cve_summary,known_cve,report_body['ServerName'])
if unknown_cves and args.vuls_ignore_unscored is False:
for unknown_cve in unknown_cves:
gen_cve_summary(cve_summary,unknown_cve,report_body['ServerName'])
final = final_cve_summary(cve_summary)
if len(final) > 0:
result = False
failReason = final
else:
result = False
failReason = "No Vuls reports found for today in " + args.vuls_report_bucket
return {'Result': result, 'failReason': failReason, 'Offenders': offenders, 'ScoredControl': scored, 'Description': description, 'ControlId': control}
def severity_to_num(severity):
if severity == 'unknown':
return 1
elif severity == 'low':
return 2
elif severity == 'medium':
return 3
elif severity == 'high':
return 4
def final_cve_summary(cve_summary):
for k,v in cve_summary.items():
if severity_to_num(v['severity']) < severity_to_num(args.vuls_min_alert_severity):
del cve_summary[k]
return cve_summary
def gen_cve_summary(summary,cve,servername):
cve_id = cve['CveDetail']['CveID']
summary[cve_id] = summary.get(cve_id) or dict()
if not summary[cve_id].get('score'):
summary[cve_id]['score'] = cve_score(cve)
if not summary[cve_id].get('severity'):
summary[cve_id]['severity'] = cve_severity(summary[cve_id]['score'])
summary[cve_id]['instances'] = summary[cve_id].get('instances') or []
summary[cve_id]['instances'].append(servername)
def cve_score(cve):
if cve['CveDetail']['Nvd']['Score'] > 0:
return cve['CveDetail']['Nvd']['Score']
elif cve['CveDetail']['Jvn']['Score'] > 0:
return cve['CveDetail']['Jvn']['Score']
else:
return -1
def cve_severity(cve_score):
if cve_score >= args.vuls_high_threshold:
return 'high'
elif cve_score >= args.vuls_medium_threshold:
return 'medium'
elif cve_score >= args.vuls_low_threshold:
return 'low'
else:
return 'unknown'
def get_account_alias():
"""AWS Account Alias
Returns:
TYPE: String
"""
try:
account_alias = IAM_CLIENT.list_account_aliases()['AccountAliases'][0]
except:
account_alias = 'could not fetch account alias'
return account_alias
def get_cred_report():
"""Summary
Returns:
TYPE: Description
"""
x = 0
status = ""
while IAM_CLIENT.generate_credential_report()['State'] != "COMPLETE":
time.sleep(2)
x += 1
# If no credentail report is delivered within this time fail the check.
if x > 10:
status = "Fail: rootUse - no CredentialReport available."
break
if "Fail" in status:
return status
response = IAM_CLIENT.get_credential_report()
responseString = str(response['Content'], 'utf-8').splitlines()
report = []
reader = csv.DictReader(responseString, delimiter=',')
for row in reader:
report.append(row)
return report
def set_evaluation(invokeEvent, mainEvent, annotation):
"""Summary
Args:
event (TYPE): Description
annotation (TYPE): Description
Returns:
TYPE: Description
"""
configClient = boto3.client('config')
if len(annotation) > 0:
configClient.put_evaluations(
Evaluations=[
{
'ComplianceResourceType': 'AWS::::Account',
'ComplianceResourceId': mainEvent['accountId'],
'ComplianceType': 'NON_COMPLIANT',
'Annotation': str(annotation),
'OrderingTimestamp': invokeEvent['notificationCreationTime']
},
],
ResultToken=mainEvent['resultToken']
)
else:
configClient.put_evaluations(
Evaluations=[
{
'ComplianceResourceType': 'AWS::::Account',
'ComplianceResourceId': mainEvent['accountId'],
'ComplianceType': 'COMPLIANT',
'OrderingTimestamp': invokeEvent['notificationCreationTime']
},
],
ResultToken=mainEvent['resultToken']
)
def json_output(controlResult):
"""Summary
Args:
controlResult (TYPE): Description
Returns:
TYPE: Description
"""
print(json.dumps(controlResult, sort_keys=False, indent=4, separators=(',', ': ')))
def shortAnnotation(controlResult):
"""Summary
Args:
controlResult (TYPE): Description
Returns:
TYPE: Description
"""
annotation = []
longAnnotation = False
for m, _ in enumerate(controlResult):
for n in range(len(controlResult[m])):
if controlResult[m][n]['Result'] is False:
if len(str(annotation)) < 220:
annotation.append(controlResult[m][n]['ControlId'])
else:
longAnnotation = True
if longAnnotation:
annotation.append("etc")
return "{\"Failed\":" + json.dumps(annotation) + "}"
else:
return "{\"Failed\":" + json.dumps(annotation) + "}"
def send_results_to_sns(controls, account):
"""Summary
Args:
controls (TYPE): Controls object
Returns:
TYPE: Description
"""
# Get correct region for the TopicARN
region = (args.sns_topic_arn.split("sns:", 1)[1]).split(":", 1)[0]
client = boto3.client('sns', region_name=region)
subject = "AWS Compliance Report - " + account + " - " + str(time.strftime("%c"))
body = json.dumps(controls, sort_keys=False, indent=4, separators=(',', ': '))
response = client.publish(
TopicArn=args.sns_topic_arn,
Subject=subject,
Message=body
)
print("SNS Response: " + str(response))
def lambda_handler(event, context):
"""Summary
Args:
event (TYPE): Description
context (TYPE): Description
Returns:
TYPE: Description
"""
try:
if event['configRuleId']:
configRule = True
# Verify correct format of event
invokingEvent = json.loads(event['invokingEvent'])
except:
configRule = False
account_alias = get_account_alias()
cred_report = get_cred_report()
controls = []
controls.append(s3_versioning_enabled())
controls.append(s3_logging_enabled())
controls.append(root_account_use(cred_report))
controls.append(mfa_on_password_enabled_iam(cred_report))
controls.append(unused_credentials(cred_report))
controls.append(old_api_keys(cred_report))
# EC2 related compliance
if account_alias not in ACCOUNTS_WITHOUT_EC2_APP_INSTANCES:
controls.append(reboots_required())
controls.append(vuls_reports())
controls.append(unix_account_last_login_reports())
if args.only_failed:
controls = list(filter(lambda x: x['Result'] == False, controls))
if args.send_report_to_sns:
if bool(controls):
send_results_to_sns(controls, account_alias)
if not bool(controls):
controls = 'OK - AWS Compliance report pass'
json_output(controls)
# Report back to Config if we detected that the script is initiated from Config Rules
if configRule:
evalAnnotation = shortAnnotation(controls)
set_evaluation(invokingEvent, event, evalAnnotation)
if __name__ == '__main__':
boto3.setup_default_session(region_name=args.region)
lambda_handler("test", "test")