-
Notifications
You must be signed in to change notification settings - Fork 465
/
Copy pathlogging-stack.ts
3048 lines (2790 loc) · 117 KB
/
logging-stack.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
import * as cdk from 'aws-cdk-lib';
import * as iam from 'aws-cdk-lib/aws-iam';
import { NagSuppressions } from 'cdk-nag';
import { Construct } from 'constructs';
import { pascalCase } from 'pascal-case';
import path from 'path';
import {
SnsTopicConfig,
VpcFlowLogsConfig,
CloudWatchLogsExclusionConfig,
CentralLogBucketConfig,
ElbLogBucketConfig,
AccessLogBucketConfig,
AssetBucketConfig,
AseaResourceType,
} from '@aws-accelerator/config';
import * as t from '@aws-accelerator/config/lib/common/types';
import {
Bucket,
BucketEncryption,
BucketEncryptionType,
BucketPolicy,
BucketPrefix,
BucketPrefixProps,
BucketReplicationProps,
CentralLogsBucket,
CloudWatchDestination,
CloudWatchLogsSubscriptionFilter,
CloudWatchToS3Firehose,
KmsEncryption,
NewCloudWatchLogEvent,
S3PublicAccessBlock,
SsmParameterLookup,
ValidateBucket,
PutSsmParameter,
BucketPolicyProps,
ServiceLinkedRole,
CloudWatchLogDataProtection,
} from '@aws-accelerator/constructs';
import {
AcceleratorImportedBucketType,
AwsPrincipalAccessesType,
BucketAccessType,
PrincipalOrgIdConditionType,
} from '@aws-accelerator/utils/lib/common-resources';
import { AcceleratorElbRootAccounts, OptInRegions } from '@aws-accelerator/utils/lib/regions';
import {
AcceleratorKeyType,
AcceleratorStack,
AcceleratorStackProps,
CloudWatchDataProtectionIdentifiers,
NagSuppressionRuleIds,
} from './accelerator-stack';
export type cloudwatchExclusionProcessedItem = {
account: string;
region: string;
excludeAll?: boolean;
logGroupNames?: string[];
};
type excludeUniqueItemType = { account: string; region: string };
type CentralLogsBucketPrincipalAndPrefixesType = {
awsPrincipalAccesses: AwsPrincipalAccessesType[];
bucketPrefixes: string[];
};
type PolicyAttachmentsType = {
policy: string;
};
export class LoggingStack extends AcceleratorStack {
private cloudwatchKey: cdk.aws_kms.IKey | undefined;
private lambdaKey: cdk.aws_kms.IKey | undefined;
private centralLogsBucket: CentralLogsBucket | undefined;
private centralLogBucketKey: cdk.aws_kms.IKey | undefined;
private centralSnsKey: cdk.aws_kms.IKey | undefined;
private snsForwarderFunction: cdk.aws_lambda.IFunction | undefined;
private importedCentralLogBucket: cdk.aws_s3.IBucket | undefined;
private importedCentralLogBucketKey: cdk.aws_kms.IKey | undefined;
constructor(scope: Construct, id: string, props: AcceleratorStackProps) {
super(scope, id, props);
// Get principal organization condition
const principalOrgIdCondition = this.getPrincipalOrgIdCondition(this.organizationId);
// Create S3 Key in all account
const s3Key = this.createS3Key();
//
// Create Managed active directory admin user secrets key
//
this.createManagedDirectoryAdminSecretsManagerKey();
//
// Create CloudWatch key
//
this.cloudwatchKey = this.createCloudWatchKey(props);
//
// Create Lambda key
//
this.lambdaKey = this.createLambdaKey(props);
//
// Create Auto scaling service linked role
//
const autoScalingSlr = this.createAutoScalingServiceLinkedRole({
cloudwatch: this.cloudwatchKey,
lambda: this.lambdaKey,
});
//
// Create AWS Cloud9 service linked role
//
const cloud9Slr = this.createAwsCloud9ServiceLinkedRole({ cloudwatch: this.cloudwatchKey, lambda: this.lambdaKey });
//
// Create KMS keys defined in config
this.createKeys(autoScalingSlr, cloud9Slr);
// Create Notification Role for FMS Notifications if enabled
this.createFMSNotificationRole();
//
// Configure block S3 public access
//
this.configureS3PublicAccessBlock(props);
//
// SNS Topics creation
//
this.createSnsTopics(props);
//
// Create S3 Bucket for Access Logs - this is required
//
const serverAccessLogsBucket = this.createOrGetServerAccessLogBucket();
//
// Create or get existing central log bucket
this.createOrGetCentralLogsBucket(serverAccessLogsBucket!, principalOrgIdCondition);
//
// Get central log bucket encryption key
//
this.centralLogBucketKey = this.getCentralLogBucketKey();
const replicationProps: BucketReplicationProps = {
destination: {
bucketName: this.centralLogsBucketName,
accountId: this.props.accountsConfig.getLogArchiveAccountId(),
keyArn: this.centralLogBucketKey.keyArn,
},
kmsKey: this.cloudwatchKey,
logRetentionInDays: this.props.globalConfig.cloudwatchLogRetentionInDays,
useExistingRoles: this.props.useExistingRoles ?? false,
acceleratorPrefix: this.props.prefixes.accelerator,
};
//
// Create VPC Flow logs destination bucket
this.createVpcFlowLogsBucket(replicationProps, s3Key, serverAccessLogsBucket);
//
// Create or get ELB access logs bucket
//
this.createOrGetElbAccessLogsBucket(principalOrgIdCondition, replicationProps);
//
// Configure CloudWatchLogs to S3 replication
//
this.configureCloudWatchLogReplication(props);
//
// Set certificate assets
//
this.setupCertificateAssets(props, principalOrgIdCondition);
//
// Create Metadata Bucket
//
this.createMetadataBucket(serverAccessLogsBucket);
//
// Create SSM Parameters
//
this.createSsmParameters();
//
// Configure Account level CloudWatch Log data protection policy
//
this.configureAccountDataProtectionPolicy();
this.logger.debug(`Stack synthesis complete`);
//
// Create NagSuppressions
//
this.addResourceSuppressionsByPath();
}
/**
* Function to configure CloudWatch log replication
* @param props {@link AcceleratorStackProps}
*
* @remarks
* First, logs receiving account will setup Kinesis DataStream and Firehose in LogArchive account home region KMS to encrypt Kinesis, Firehose and any Lambda environment variables for CloudWatchLogs to S3 replication
*
* CloudWatch logs replication requires Kinesis Data stream, Firehose and AWS Organizations.
* Some or all of these services may not be available in all regions.
* Only deploy in standard and GovCloud partitions
*
* Check to see if users specified enable on CloudWatch logs in global config.
* Defaults to true if undefined. If set to false, no resources are created.
*/
private configureCloudWatchLogReplication(props: AcceleratorStackProps): void {
if (props.globalConfig.logging.cloudwatchLogs?.enable ?? true) {
if (props.partition === 'aws' || props.partition === 'aws-us-gov' || props.partition === 'aws-cn') {
if (cdk.Stack.of(this).account === props.accountsConfig.getLogArchiveAccountId()) {
const receivingLogs = this.cloudwatchLogReceivingAccount(this.centralLogsBucketName, this.lambdaKey);
const creatingLogs = this.cloudwatchLogCreatingAccount();
// Log receiving setup should be complete before logs creation setup can start or else there will be errors about destination not ready.
creatingLogs.node.addDependency(receivingLogs);
} else {
// Any account in LZA needs to setup log subscriptions for CloudWatch Logs
// The destination needs to be present before its setup
this.cloudwatchLogCreatingAccount();
}
}
}
}
/**
* Function to create or get ELB access log bucket
* @param principalOrgIdCondition {@link PrincipalOrgIdConditionType}
* @param replicationProps {@link BucketReplicationProps}
* @returns
*/
private createOrGetElbAccessLogsBucket(
principalOrgIdCondition: PrincipalOrgIdConditionType,
replicationProps?: BucketReplicationProps,
): cdk.aws_s3.IBucket | undefined {
/**
* Create S3 Bucket for ELB Access Logs, this is created in log archive account
* For ELB to write access logs bucket is needed to have SSE-S3 server-side encryption
*/
if (cdk.Stack.of(this).account === this.props.accountsConfig.getLogArchiveAccountId()) {
const elbAccountId = this.getElbAccountId();
if (this.props.globalConfig.logging.elbLogBucket?.importedBucket) {
const bucket = this.getImportedBucket(
this.props.globalConfig.logging.elbLogBucket.importedBucket.name,
AcceleratorImportedBucketType.ELB_LOGS_BUCKET,
's3',
).bucket;
this.updateImportedBucketResourcePolicy({
bucketConfig: this.props.globalConfig.logging.elbLogBucket,
importedBucket: bucket,
bucketType: AcceleratorImportedBucketType.ELB_LOGS_BUCKET,
overridePolicyFile: this.props.globalConfig.logging.elbLogBucket.customPolicyOverrides?.policy,
principalOrgIdCondition,
elbAccountId: elbAccountId,
organizationId: this.organizationId,
});
return bucket;
} else {
return this.createElbAccessLogsBucket(replicationProps, elbAccountId);
}
}
return undefined;
}
/**
* Function to get ELB account id
* @returns
*/
private getElbAccountId() {
let elbAccountId = undefined;
if (AcceleratorElbRootAccounts.get(cdk.Stack.of(this).region)) {
elbAccountId = AcceleratorElbRootAccounts.get(cdk.Stack.of(this).region);
}
if (this.props.networkConfig.elbAccountIds?.find(item => item.region === cdk.Stack.of(this).region)) {
elbAccountId = this.props.networkConfig.elbAccountIds?.find(
item => item.region === cdk.Stack.of(this).region,
)!.accountId;
}
return elbAccountId;
}
/**
* Function to create ELB access logs bucket
* @param replicationProps {@link BucketReplicationProps}
* @param elbAccountId string
*
* @returns bucket {@link cdk.aws_s3.IBucket} | undefined
*
* @remarks
* Create S3 Bucket for ELB Access Logs, this is created in log archive account.
* For ELB to write access logs bucket is needed to have SSE-S3 server-side encryption
*/
private createElbAccessLogsBucket(
replicationProps?: BucketReplicationProps,
elbAccountId?: string,
): cdk.aws_s3.IBucket | undefined {
const elbAccessLogsBucket = new Bucket(this, 'ElbAccessLogsBucket', {
encryptionType: BucketEncryptionType.SSE_S3, // ELB Access Logs bucket does not support SSE-KMS
s3BucketName: this.getElbLogsBucketName(),
replicationProps,
s3LifeCycleRules: this.getS3LifeCycleRules(this.props.globalConfig.logging.elbLogBucket?.lifecycleRules),
});
// To make sure central log bucket created before elb access log bucket, this is required when logging stack executes in home region
if (this.centralLogsBucket) {
elbAccessLogsBucket.node.addDependency(this.centralLogsBucket);
}
// AwsSolutions-IAM5: The IAM entity contains wildcard permissions and does not have a cdk_nag rule suppression with evidence for those permission.
this.nagSuppressionInputs.push({
id: NagSuppressionRuleIds.IAM5,
details: [
{
path:
`/${this.stackName}/ElbAccessLogsBucket/ElbAccessLogsBucketReplication/` +
pascalCase(this.centralLogsBucketName) +
'-ReplicationRole/DefaultPolicy/Resource',
reason: 'Allows only specific policy.',
},
],
});
let elbPrincipal;
if (elbAccountId) {
elbPrincipal = new iam.AccountPrincipal(`${elbAccountId}`);
} else {
elbPrincipal = new iam.ServicePrincipal(`logdelivery.elasticloadbalancing.amazonaws.com`);
}
const policies = [
new cdk.aws_iam.PolicyStatement({
sid: 'Allow get acl access for SSM principal',
effect: iam.Effect.ALLOW,
actions: ['s3:GetBucketAcl'],
principals: [new iam.ServicePrincipal('ssm.amazonaws.com')],
resources: [`${elbAccessLogsBucket.getS3Bucket().bucketArn}`],
}),
new cdk.aws_iam.PolicyStatement({
sid: 'Allow write access for ELB Account principal',
effect: iam.Effect.ALLOW,
actions: ['s3:PutObject'],
principals: [elbPrincipal],
resources: [`${elbAccessLogsBucket.getS3Bucket().bucketArn}/*`],
}),
new cdk.aws_iam.PolicyStatement({
sid: 'Allow write access for delivery logging service principal',
effect: iam.Effect.ALLOW,
actions: ['s3:PutObject'],
principals: [new iam.ServicePrincipal('delivery.logs.amazonaws.com')],
resources: [`${elbAccessLogsBucket.getS3Bucket().bucketArn}/*`],
conditions: {
StringEquals: {
's3:x-amz-acl': 'bucket-owner-full-control',
},
},
}),
new cdk.aws_iam.PolicyStatement({
sid: 'Allow read bucket ACL access for delivery logging service principal',
effect: iam.Effect.ALLOW,
actions: ['s3:GetBucketAcl'],
principals: [new iam.ServicePrincipal('delivery.logs.amazonaws.com')],
resources: [`${elbAccessLogsBucket.getS3Bucket().bucketArn}`],
}),
];
policies.forEach(item => {
elbAccessLogsBucket.getS3Bucket().addToResourcePolicy(item);
});
elbAccessLogsBucket.getS3Bucket().addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
sid: 'Allow Organization principals to use of the bucket',
effect: cdk.aws_iam.Effect.ALLOW,
actions: ['s3:GetBucketLocation', 's3:PutObject'],
principals: [new cdk.aws_iam.AnyPrincipal()],
resources: [
`${elbAccessLogsBucket.getS3Bucket().bucketArn}`,
`${elbAccessLogsBucket.getS3Bucket().bucketArn}/*`,
],
conditions: {
StringEquals: {
...this.getPrincipalOrgIdCondition(this.organizationId),
},
},
}),
);
// AwsSolutions-S1: The S3 Bucket has server access logs disabled.
this.nagSuppressionInputs.push({
id: NagSuppressionRuleIds.S1,
details: [
{
path: `${this.stackName}/ElbAccessLogsBucket/Resource/Resource`,
reason: 'ElbAccessLogsBucket has server access logs disabled till the task for access logging completed.',
},
],
});
this.elbLogBucketAddResourcePolicies(elbAccessLogsBucket.getS3Bucket());
return elbAccessLogsBucket.getS3Bucket();
}
/**
* Function to get or create server access log bucket
* @returns bucket {@link cdk.aws_s3.IBucket} | undefined
*/
private createOrGetServerAccessLogBucket(): cdk.aws_s3.IBucket | undefined {
if (this.props.globalConfig.logging.accessLogBucket?.importedBucket) {
const bucket = this.getImportedBucket(
this.props.globalConfig.logging.accessLogBucket.importedBucket.name,
AcceleratorImportedBucketType.SERVER_ACCESS_LOGS_BUCKET,
's3',
).bucket;
this.updateImportedBucketResourcePolicy({
bucketConfig: this.props.globalConfig.logging.accessLogBucket,
importedBucket: bucket,
bucketType: AcceleratorImportedBucketType.SERVER_ACCESS_LOGS_BUCKET,
overridePolicyFile: this.props.globalConfig.logging.accessLogBucket.customPolicyOverrides?.policy,
organizationId: this.organizationId,
});
return bucket;
}
if (!this.isAccessLogsBucketEnabled) {
this.logger.info(
`AWS S3 access log bucket disable for ${cdk.Stack.of(this).account} account in ${
cdk.Stack.of(this).region
} region, server access logs bucket creation excluded`,
);
return undefined;
}
return this.createServerAccessLogBucket();
}
/**
* Function to create server access log bucket.
* @returns bucket {@link cdk.aws_s3.IBucket}
*/
private createServerAccessLogBucket(): cdk.aws_s3.IBucket {
//
// Create S3 Bucket for Access Logs - this is required
//
const serverAccessLogsBucket = new Bucket(this, 'AccessLogsBucket', {
encryptionType: BucketEncryptionType.SSE_S3, // Server access logging does not support SSE-KMS
s3BucketName: `${this.acceleratorResourceNames.bucketPrefixes.s3AccessLogs}-${cdk.Stack.of(this).account}-${
cdk.Stack.of(this).region
}`,
s3LifeCycleRules: this.getS3LifeCycleRules(this.props.globalConfig.logging.accessLogBucket?.lifecycleRules),
});
// AwsSolutions-S1: The S3 Bucket has server access logs disabled.
this.nagSuppressionInputs.push({
id: NagSuppressionRuleIds.S1,
details: [
{
path: `${this.stackName}/AccessLogsBucket/Resource/Resource`,
reason: 'AccessLogsBucket has server access logs disabled till the task for access logging completed.',
},
],
});
serverAccessLogsBucket.getS3Bucket().addToResourcePolicy(
new iam.PolicyStatement({
sid: 'Allow write access for logging service principal',
effect: iam.Effect.ALLOW,
actions: ['s3:PutObject'],
principals: [new iam.ServicePrincipal('logging.s3.amazonaws.com')],
resources: [serverAccessLogsBucket.getS3Bucket().arnForObjects('*')],
conditions: {
StringEquals: {
'aws:SourceAccount': cdk.Stack.of(this).account,
},
},
}),
);
return serverAccessLogsBucket.getS3Bucket();
}
/**
* Function to get existing or solution defined Central Log Bucket Encryption Key
* @returns cdk.aws_kms.IKey
*
* @remarks
* For stacks in logging account and centralizedLoggingRegion region, bucket will be present to get key arn.
* All other environment stacks will need custom resource to get key arn from ssm parameter.
*/
private getCentralLogBucketKey(): cdk.aws_kms.IKey {
if (this.props.globalConfig.logging.centralLogBucket?.importedBucket?.name) {
if (this.importedCentralLogBucket) {
return this.importedCentralLogBucketKey!;
} else {
return this.getAcceleratorKey(AcceleratorKeyType.IMPORTED_CENTRAL_LOG_BUCKET, this.cloudwatchKey)!;
}
} else {
if (this.centralLogsBucket) {
return this.centralLogsBucket.getS3Bucket().getKey();
} else {
return this.getAcceleratorKey(AcceleratorKeyType.CENTRAL_LOG_BUCKET, this.cloudwatchKey)!;
}
}
}
/**
* Function to create CloudWatch key
* @param props {@link AcceleratorStackProps}
* @returns cdk.aws_kms.IKey
*/
private createCloudWatchKey(props: AcceleratorStackProps): cdk.aws_kms.IKey | undefined {
if (!this.isCloudWatchLogsGroupCMKEnabled) {
this.logger.info(
`CloudWatch Encryption CMK disable for ${cdk.Stack.of(this).account} account in ${
cdk.Stack.of(this).region
} region, CMK creation excluded`,
);
return undefined;
}
// Create kms key for CloudWatch logs the CloudWatch key. Management account home region this key was created in prepare stack
if (
cdk.Stack.of(this).account === props.accountsConfig.getManagementAccountId() &&
(cdk.Stack.of(this).region === this.props.globalConfig.homeRegion ||
cdk.Stack.of(this).region === this.props.globalRegion)
) {
return this.getAcceleratorKey(AcceleratorKeyType.CLOUDWATCH_KEY);
} else {
const cloudwatchKey = new cdk.aws_kms.Key(this, 'AcceleratorCloudWatchKey', {
alias: this.acceleratorResourceNames.customerManagedKeys.cloudWatchLog.alias,
description: this.acceleratorResourceNames.customerManagedKeys.cloudWatchLog.description,
enableKeyRotation: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
cloudwatchKey.addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
sid: `Allow Cloudwatch logs to use the encryption key`,
principals: [new cdk.aws_iam.ServicePrincipal(`logs.${cdk.Stack.of(this).region}.amazonaws.com`)],
actions: ['kms:Encrypt*', 'kms:Decrypt*', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:Describe*'],
resources: ['*'],
conditions: {
ArnLike: {
'kms:EncryptionContext:aws:logs:arn': `arn:${this.props.partition}:logs:${
cdk.Stack.of(this).region
}:*:log-group:*`,
},
},
}),
);
cloudwatchKey.addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
sid: `Allow EventBridge to send to encrypted CloudWatch log groups`,
principals: [new cdk.aws_iam.ServicePrincipal('events.amazonaws.com')],
actions: ['kms:GenerateDataKey', 'kms:Decrypt'],
resources: ['*'],
conditions: {
StringEqualsIfExists: {
'aws:SourceAccount': cdk.Stack.of(this).account,
},
},
}),
);
this.ssmParameters.push({
logicalId: 'AcceleratorCloudWatchKmsArnParameter',
parameterName: this.acceleratorResourceNames.parameters.cloudWatchLogCmkArn,
stringValue: cloudwatchKey.keyArn,
});
return cloudwatchKey;
}
}
/**
* Function to create Lambda key
* @param props {@link AcceleratorStackProps}
* @returns cdk.aws_kms.IKey
*/
private createLambdaKey(props: AcceleratorStackProps): cdk.aws_kms.IKey | undefined {
if (!this.isLambdaCMKEnabled) {
this.logger.info(
`Lambda Encryption CMK disable for ${cdk.Stack.of(this).account} account in ${
cdk.Stack.of(this).region
} region, CMK creation excluded`,
);
return undefined;
}
// Create kms key for Lambda environment encryption
// the Lambda environment encryption key for the management account
// in the home region is created in the prepare stack
if (
cdk.Stack.of(this).account === props.accountsConfig.getManagementAccountId() &&
(cdk.Stack.of(this).region === this.props.globalConfig.homeRegion ||
cdk.Stack.of(this).region === this.props.globalRegion)
) {
return this.getAcceleratorKey(AcceleratorKeyType.LAMBDA_KEY);
} else {
const key = new cdk.aws_kms.Key(this, 'AcceleratorLambdaKey', {
alias: this.acceleratorResourceNames.customerManagedKeys.lambda.alias,
description: this.acceleratorResourceNames.customerManagedKeys.lambda.description,
enableKeyRotation: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
this.ssmParameters.push({
logicalId: 'AcceleratorLambdaKmsArnParameter',
parameterName: this.acceleratorResourceNames.parameters.lambdaCmkArn,
stringValue: key.keyArn,
});
return key;
}
}
/**
* Function to configure block S3 public access
* @param props {@link AcceleratorStackProps}
* @returns S3PublicAccessBlock | undefined
*/
private configureS3PublicAccessBlock(props: AcceleratorStackProps): S3PublicAccessBlock | undefined {
//
// Block Public Access; S3 is global, only need to call in home region. This is done in the
// logging-stack instead of the security-stack since initial buckets are created in this stack.
//
let s3PublicAccessBlock: S3PublicAccessBlock | undefined;
if (
cdk.Stack.of(this).region === this.props.globalConfig.homeRegion &&
!this.isAccountExcluded(props.securityConfig.centralSecurityServices.s3PublicAccessBlock.excludeAccounts ?? [])
) {
if (props.securityConfig.centralSecurityServices.s3PublicAccessBlock.enable) {
s3PublicAccessBlock = new S3PublicAccessBlock(this, 'S3PublicAccessBlock', {
blockPublicAcls: true,
blockPublicPolicy: true,
ignorePublicAcls: true,
restrictPublicBuckets: true,
accountId: cdk.Stack.of(this).account,
kmsKey: this.cloudwatchKey,
logRetentionInDays: props.globalConfig.cloudwatchLogRetentionInDays,
});
}
}
return s3PublicAccessBlock;
}
/**
* Function to create SNS topics
* @param props {@link AcceleratorStackProps}
*/
private createSnsTopics(props: AcceleratorStackProps): void {
// SNS Topics creation
if (
props.globalConfig.snsTopics &&
cdk.Stack.of(this).account === props.accountsConfig.getLogArchiveAccountId() &&
!this.isRegionExcluded(props.globalConfig.snsTopics?.deploymentTargets.excludedRegions ?? [])
) {
this.createCentralSnsKey();
for (const snsTopic of props.globalConfig.snsTopics?.topics ?? []) {
this.createLoggingAccountSnsTopic(snsTopic, this.centralSnsKey!);
}
}
if (
this.isIncluded(props.globalConfig.snsTopics?.deploymentTargets ?? new t.DeploymentTargets()) &&
cdk.Stack.of(this).account !== props.accountsConfig.getLogArchiveAccountId()
) {
const snsKey = this.createSnsKey();
this.createSnsForwarderFunction();
for (const snsTopic of props.globalConfig.snsTopics?.topics ?? []) {
this.createSnsTopic(snsTopic, snsKey);
}
}
}
/**
* Function to create S3 Key
* @returns cdk.aws_kms.IKey | undefined
*/
private createS3Key(): cdk.aws_kms.IKey | undefined {
if (!this.isS3CMKEnabled) {
this.logger.info(
`AWS S3 Encryption CMK disable for ${cdk.Stack.of(this).account} account in ${
cdk.Stack.of(this).region
} region, CMK creation excluded`,
);
return undefined;
}
//
// Crete S3 key in every account except audit account,
// this is required for SSM automation to get right KMS key to encrypt unencrypted bucket
if (cdk.Stack.of(this).account !== this.props.accountsConfig.getAuditAccountId()) {
this.logger.debug(`Create S3 Key`);
const s3Key = new cdk.aws_kms.Key(this, 'Accelerator3Key', {
alias: this.acceleratorResourceNames.customerManagedKeys.s3.alias,
description: this.acceleratorResourceNames.customerManagedKeys.s3.description,
enableKeyRotation: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
s3Key.addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
sid: `Allow S3 to use the encryption key`,
principals: [new cdk.aws_iam.AnyPrincipal()],
actions: ['kms:Encrypt', 'kms:Decrypt', 'kms:ReEncrypt*', 'kms:GenerateDataKey', 'kms:Describe*'],
resources: ['*'],
conditions: {
StringEquals: {
'kms:ViaService': `s3.${cdk.Stack.of(this).region}.amazonaws.com`,
...this.getPrincipalOrgIdCondition(this.organizationId),
},
},
}),
);
s3Key.addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
sid: 'Allow AWS Services to encrypt and describe logs',
actions: [
'kms:Decrypt',
'kms:DescribeKey',
'kms:Encrypt',
'kms:GenerateDataKey',
'kms:GenerateDataKeyPair',
'kms:GenerateDataKeyPairWithoutPlaintext',
'kms:GenerateDataKeyWithoutPlaintext',
'kms:ReEncryptFrom',
'kms:ReEncryptTo',
],
principals: [new cdk.aws_iam.ServicePrincipal(`delivery.logs.amazonaws.com`)],
resources: ['*'],
}),
);
this.ssmParameters.push({
logicalId: 'AcceleratorS3KmsArnParameter',
parameterName: this.acceleratorResourceNames.parameters.s3CmkArn,
stringValue: s3Key.keyArn,
});
return s3Key;
} else {
return this.createAuditAccountS3Key();
}
}
/**
* Function to create Audit account S3 bucket encryption Key
* @returns cdk.aws_kms.IKey | undefined
*/
private createAuditAccountS3Key(): cdk.aws_kms.IKey | undefined {
if (!this.isS3CMKEnabled) {
this.logger.info(
`AWS S3 Encryption CMK disable for ${cdk.Stack.of(this).account} account in ${
cdk.Stack.of(this).region
} region, CMK creation excluded`,
);
return undefined;
}
this.logger.debug(`Create S3 Key`);
const s3Key = new cdk.aws_kms.Key(this, 'AcceleratorAuditS3Key', {
alias: this.acceleratorResourceNames.customerManagedKeys.s3.alias,
description: this.acceleratorResourceNames.customerManagedKeys.s3.description,
enableKeyRotation: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
s3Key.addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
sid: `Allow S3 to use the encryption key`,
principals: [new cdk.aws_iam.AnyPrincipal()],
actions: ['kms:Encrypt', 'kms:Decrypt', 'kms:ReEncrypt*', 'kms:GenerateDataKey', 'kms:Describe*'],
resources: ['*'],
conditions: {
StringEquals: {
'kms:ViaService': `s3.${cdk.Stack.of(this).region}.amazonaws.com`,
...this.getPrincipalOrgIdCondition(this.organizationId),
},
},
}),
);
s3Key.addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
sid: 'Allow services to confirm encryption',
principals: [new cdk.aws_iam.AnyPrincipal()],
actions: ['kms:Decrypt', 'kms:GenerateDataKey'],
resources: ['*'],
conditions: {
StringEquals: {
...this.getPrincipalOrgIdCondition(this.organizationId),
},
},
}),
);
const allowedServicePrincipals: { name: string; principal: string }[] = [];
allowedServicePrincipals.push({ name: 'CloudTrail', principal: 'cloudtrail.amazonaws.com' });
if (this.props.securityConfig.centralSecurityServices.auditManager?.enable) {
allowedServicePrincipals.push({ name: 'AuditManager', principal: 'auditmanager.amazonaws.com' });
s3Key.addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
sid: `Allow Audit Manager service to provision encryption key grants`,
principals: [new cdk.aws_iam.AnyPrincipal()],
actions: ['kms:CreateGrant'],
conditions: {
StringLike: {
'kms:ViaService': 'auditmanager.*.amazonaws.com',
...this.getPrincipalOrgIdCondition(this.organizationId),
},
Bool: { 'kms:GrantIsForAWSResource': 'true' },
},
resources: ['*'],
}),
);
}
allowedServicePrincipals.forEach(item => {
s3Key.addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
sid: `Allow ${item.name} service to use the encryption key`,
principals: [new cdk.aws_iam.ServicePrincipal(item.principal)],
actions: ['kms:Encrypt', 'kms:Decrypt', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:DescribeKey'],
resources: ['*'],
}),
);
});
this.ssmParameters.push({
logicalId: 'AcceleratorS3KmsArnParameter',
parameterName: this.acceleratorResourceNames.parameters.s3CmkArn,
stringValue: s3Key.keyArn,
});
return s3Key;
}
/**
* Function to get VPC flow logs configuration when any VPC have S3 flow logs destination
*/
private getS3FlowLogsDestinationConfig(): VpcFlowLogsConfig | undefined {
let vpcFlowLogs: VpcFlowLogsConfig | undefined;
for (const vpcItem of [...this.props.networkConfig.vpcs, ...(this.props.networkConfig.vpcTemplates ?? [])] ?? []) {
// Get account IDs
const vpcAccountIds = this.getVpcAccountIds(vpcItem);
if (vpcAccountIds.includes(cdk.Stack.of(this).account) && vpcItem.region === cdk.Stack.of(this).region) {
if (vpcItem.vpcFlowLogs) {
vpcFlowLogs = vpcItem.vpcFlowLogs;
} else {
vpcFlowLogs = this.props.networkConfig.vpcFlowLogs;
}
if (vpcFlowLogs && vpcFlowLogs.destinations.includes('s3')) {
return vpcFlowLogs;
}
}
}
return undefined;
}
/**
* Function to create VPC FlowLogs bucket.
* This bucket depends on Central Logs bucket and Server access logs bucket.
* This bucket also depends on local S3 key.
* @param replicationProps {@link BucketReplicationProps}
* @param s3Key {@link cdk.aws_kms.IKey} | undefined
* @param serverAccessLogsBucket {@link cdk.aws_s3.IBucket} | undefined
*/
private createVpcFlowLogsBucket(
replicationProps: BucketReplicationProps,
s3Key?: cdk.aws_kms.IKey,
serverAccessLogsBucket?: cdk.aws_s3.IBucket,
) {
const vpcFlowLogsConfig = this.getS3FlowLogsDestinationConfig();
if (vpcFlowLogsConfig) {
this.logger.info(`Create S3 bucket for VPC flow logs destination`);
const vpcFlowLogsBucket = new Bucket(this, 'AcceleratorVpcFlowLogsBucket', {
encryptionType: this.isS3CMKEnabled ? BucketEncryptionType.SSE_KMS : BucketEncryptionType.SSE_S3,
s3BucketName: `${this.acceleratorResourceNames.bucketPrefixes.vpcFlowLogs}-${cdk.Stack.of(this).account}-${
cdk.Stack.of(this).region
}`,
kmsKey: s3Key,
serverAccessLogsBucket,
s3LifeCycleRules: this.getS3LifeCycleRules(vpcFlowLogsConfig.destinationsConfig?.s3?.lifecycleRules),
replicationProps: replicationProps,
});
if (!serverAccessLogsBucket) {
// AwsSolutions-S1: The S3 Bucket has server access logs disabled
this.nagSuppressionInputs.push({
id: NagSuppressionRuleIds.S1,
details: [
{
path: `/${this.stackName}/AcceleratorVpcFlowLogsBucket/Resource/Resource`,
reason: 'Due to configuration settings, server access logs have been disabled.',
},
],
});
}
vpcFlowLogsBucket.getS3Bucket().addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
sid: 'Allow read bucket ACL access for delivery logging service principal',
effect: cdk.aws_iam.Effect.ALLOW,
actions: ['s3:GetBucketAcl'],
principals: [new cdk.aws_iam.ServicePrincipal('delivery.logs.amazonaws.com')],
resources: [`${vpcFlowLogsBucket.getS3Bucket().bucketArn}`],
}),
);
vpcFlowLogsBucket.getS3Bucket().addToResourcePolicy(
new cdk.aws_iam.PolicyStatement({
principals: [new cdk.aws_iam.ServicePrincipal('delivery.logs.amazonaws.com')],
actions: ['s3:GetBucketAcl', 's3:ListBucket'],
resources: [vpcFlowLogsBucket.getS3Bucket().bucketArn],
}),
);
// AwsSolutions-IAM5: The IAM entity contains wildcard permissions and does not have a cdk_nag rule suppression with evidence for those permission.
this.nagSuppressionInputs.push({
id: NagSuppressionRuleIds.IAM5,
details: [
{
path:
`${this.stackName}/AcceleratorVpcFlowLogsBucket/AcceleratorVpcFlowLogsBucketReplication/` +
pascalCase(this.centralLogsBucketName) +
'-ReplicationRole/DefaultPolicy/Resource',
reason: 'Allows only specific policy.',
},
],
});
this.ssmParameters.push({
logicalId: 'AcceleratorVpcFlowLogsBucketArnParameter',
parameterName: this.acceleratorResourceNames.parameters.flowLogsDestinationBucketArn,
stringValue: vpcFlowLogsBucket.getS3Bucket().bucketArn,
});
}
}
private cloudwatchLogReceivingAccount(centralLogsBucketName: string, lambdaKey?: cdk.aws_kms.IKey) {
const logsReplicationKmsKey = new cdk.aws_kms.Key(this, 'LogsReplicationKey', {
alias: this.acceleratorResourceNames.customerManagedKeys.cloudWatchLogReplication.alias,
description: this.acceleratorResourceNames.customerManagedKeys.cloudWatchLogReplication.description,
enableKeyRotation: true,
// kms is used to encrypt kinesis data stream,
// unlike data store like s3, rds, dynamodb no snapshot/object is encrypted
// it can be destroyed as encrypts service
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
// // Create Kinesis Data Stream
// Kinesis Stream - data stream which will get data from CloudWatch logs
const logsKinesisStreamCfn = new cdk.aws_kinesis.CfnStream(this, 'LogsKinesisStreamCfn', {
retentionPeriodHours: 24,
shardCount: 1,
streamEncryption: {
encryptionType: 'KMS',
keyId: logsReplicationKmsKey.keyArn,
},
});
const logsKinesisStream = cdk.aws_kinesis.Stream.fromStreamArn(
this,
'LogsKinesisStream',
logsKinesisStreamCfn.attrArn,
);
// LogsKinesisStream/Resource AwsSolutions-KDS3