This repository was archived by the owner on Dec 31, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 234
Expand file tree
/
Copy pathconvert-config.ts
More file actions
3847 lines (3681 loc) · 154 KB
/
convert-config.ts
File metadata and controls
3847 lines (3681 loc) · 154 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2023 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 fs from 'fs';
import { posix, default as path } from 'path';
import * as yaml from 'js-yaml';
import _ from 'lodash';
import {
AcceleratorConfig,
CertificateConfig,
GlobalOptionsConfig,
IamPolicyConfig,
IamRoleConfig,
IamUserConfig,
ImportCertificateConfigType,
NaclConfig,
PcxRouteConfig,
ResolvedVpcConfig,
RouteTableConfig,
SecurityGroupRuleConfig,
SecurityGroupSourceConfig,
SubnetConfig,
SubnetDefinitionConfig,
SubnetSourceConfig,
TgwDeploymentConfig,
TransitGatewayRouteConfig,
VpcConfig,
VpcFlowLogsDestinationConfig,
} from './asea-config';
import { loadAseaConfig } from './asea-config/load';
import * as WriteToSourcesTypes from './common//utils/types/writeToSourcesTypes';
import { DynamoDB } from './common/aws/dynamodb';
import { KMS } from './common/aws/kms';
import { Organizations } from './common/aws/organizations';
import { S3 } from './common/aws/s3';
import { SSM } from './common/aws/ssm';
import { STS } from './common/aws/sts';
import { Account, getAccountId } from './common/outputs/accounts';
import {
SubnetAssignedCidr,
VpcAssignedCidr,
loadSubnetAssignedCidrs,
loadVpcAssignedCidrs,
} from './common/outputs/load-assigned-cidrs';
import { StackOutput, findValuesFromOutputs, loadOutputs } from './common/outputs/load-outputs';
import { loadAccounts } from './common/utils/accounts';
import {
createConfigRuleName,
createNaclName,
createNatGatewayName,
createNetworkFirewallName,
createNetworkFirewallPolicyName,
createNetworkFirewallRuleGroupName,
createRouteTableName,
createScpName,
createSsmDocumentName,
createSubnetName,
createTgwAttachName,
createVpcName,
nfwRouteName,
peeringConnectionName,
securityGroupName,
subnetsCidrsTableName,
transitGatewayName,
transitGatewayPeerName,
transitGatewayRouteTableName,
vpcCidrsTableName,
} from './common/utils/naming';
import * as ConvertConfigTypes from './common/utils/types/convertConfigTypes';
import { WriteToSources } from './common/utils/writeToSources';
import { Config } from './config';
import { AccountsConfig, AccountsConfigType } from './config/accounts-config';
import { Region, ShareTargets } from './config/common-types';
import {
BlockDeviceMappingItem,
CustomizationsConfig,
CustomizationsConfigTypes,
Ec2FirewallConfig,
Ec2FirewallInstanceConfig,
LaunchTemplateConfig,
NetworkInterfaceItemConfig,
} from './config/customizations-config';
import { GlobalConfig } from './config/global-config';
import {
AssumedByConfig,
GroupConfig,
IamConfig,
PolicySetConfigType,
RoleSetConfigType,
UserConfig,
} from './config/iam-config';
import {
NetworkConfig,
NfwFirewallConfig,
NfwFirewallPolicyConfig,
NfwLoggingConfig,
NfwRuleGroupConfig,
NfwRuleSourceCustomActionConfig,
NfwRuleSourceStatelessRuleConfig,
} from './config/network-config';
import { OrganizationConfig, OrganizationConfigType } from './config/organization-config';
import { AwsConfigRule, SecurityConfig } from './config/security-config';
import { ConfigCheck } from './inventory/config-checks';
const IAM_POLICY_CONFIG_PATH = 'iam-policy';
const SCP_CONFIG_PATH = 'scp';
const SSM_DOCUMENTS_CONFIG_PATH = 'ssm-documents';
const CONFIG_RULES_PATH = 'config-rules';
const LZA_SCP_CONFIG_PATH = 'service-control-policies';
const LZA_CONFIG_RULES = 'custom-config-rules';
const LZA_BUCKET_POLICY = 'bucket-policies';
const LZA_KMS_POLICY = 'kms-policies';
const LZA_IAM_POLICY_CONFIG_PATH = 'iam-policies';
const LZA_CLOUDFORMATION = 'cloudformation';
const LOG_RETENTION = [
1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, 3653,
];
/**
* Assets required for LZA configuration
* - Config Rule remediation role policies
*/
const ConfigRuleRemediationAssets: { [key: string]: string } = {
'Attach-IAM-Instance-Profile': posix.join(LZA_CONFIG_RULES, 'attach-ec2-instance-profile-remediation-role.json'),
'Attach-IAM-Role-Policy': posix.join(LZA_CONFIG_RULES, 'ec2-instance-profile-permissions-remediation-role.json'),
'SSM-ELB-Enable-Logging': posix.join(LZA_CONFIG_RULES, 'elb-logging-enabled-remediation-role.json'),
'Put-S3-Encryption': posix.join(LZA_CONFIG_RULES, 'bucket-sse-enabled-remediation-role.json'),
};
const ConfigRuleDetectionAssets: { [key: string]: string } = {
'EC2-INSTANCE-PROFILE': posix.join(LZA_CONFIG_RULES, 'attach-ec2-instance-profile-detection-role.json'),
'EC2-INSTANCE-PROFILE-PERMISSIONS': posix.join(
LZA_CONFIG_RULES,
'ec2-instance-profile-permissions-detection-role.json',
),
};
const CloudFormationAssets: { [key: string]: string } = {
'ALB-IP-FORWARDING': posix.join(LZA_CLOUDFORMATION, 'AlbIpForwardingStack.template.json'),
};
const SnsFindingTypesDict = {
Low: 'Low',
Medium: 'Medium',
High: 'High',
Critical: 'High',
INFORMATIONAL: 'Low',
None: 'Low',
};
type DocumentSet = {
shareTargets: { organizationalUnits?: string[]; accounts?: string[] };
documents: { name: string; template: string }[];
};
type AccountKeyMapping = {
[key: string]: string;
}
const accountKeyMapping: AccountKeyMapping = {
'log-archive': 'LogArchive',
'audit': 'Security'
};
export class ConvertAseaConfig {
private localUpdateOnly = false; // This is an option to not write config changes to codecommit, used only for development like yarn run convert-config local-update-only. Default is true
private enableTerminationProtection = false;
private readonly aseaConfigRepositoryName: string;
private readonly region: string;
private readonly aseaPrefix: string;
private readonly centralBucketName: string;
private readonly lzaConfigRepositoryName: string;
private readonly parametersTable: string;
private readonly mappingFileBucket: string;
private readonly localConfigFilePath?: string;
private readonly s3: S3;
private readonly sts: STS;
private readonly dynamoDb: DynamoDB;
private readonly organizations = new Organizations();
private readonly acceleratorName: string;
private readonly assumeRoleName: string;
private readonly writeFilesConfig: WriteToSourcesTypes.WriteToSourcesConfig;
private readonly ouToNestedOuMap: Map<string, Set<string>> = new Map();
private accounts: Account[] = [];
private outputs: StackOutput[] = [];
private vpcAssignedCidrs: VpcAssignedCidr[] = [];
private subnetAssignedCidrs: SubnetAssignedCidr[] = [];
private vpcConfigs: ResolvedVpcConfig[] = [];
private globalOptions: GlobalOptionsConfig | undefined;
private ssmClients: { [region: string]: SSM } = {};
private lzaAccountKeys: string[] | undefined;
private regionsWithoutVpc: string[] = [];
private accountsWithoutVpc: string[] = [];
private accountsWithVpc: Set<string> = new Set<string>([]);
private writeToSources: WriteToSources;
private configCheck: ConfigCheck = new ConfigCheck();
private documentSets: DocumentSet[] = [];
constructor(config: Config) {
this.localUpdateOnly = config.localOnlyWrites ?? false;
this.enableTerminationProtection = config.enableTerminationProtection ?? false;
this.aseaConfigRepositoryName = config.repositoryName;
this.localConfigFilePath = config.localConfigFilePath ?? undefined;
this.region = config.homeRegion;
this.centralBucketName = config.centralBucket!;
this.aseaPrefix = config.aseaPrefix!.endsWith('-') ? config.aseaPrefix! : `${config.aseaPrefix}-`;
this.parametersTable = `${this.aseaPrefix}Parameters`;
this.acceleratorName = config.acceleratorName!;
this.sts = new STS();
this.s3 = new S3(undefined, this.region);
this.dynamoDb = new DynamoDB(undefined, this.region);
this.lzaConfigRepositoryName = config.lzaConfigRepositoryName;
this.mappingFileBucket = config.mappingBucketName;
this.assumeRoleName = config.assumeRoleName ?? 'OrganizationAccountAccessRole';
this.writeFilesConfig = {
localOnly: this.localUpdateOnly,
codeCommitConfig: {
branch: 'main',
repository: this.lzaConfigRepositoryName,
},
s3Config: {
bucket: this.mappingFileBucket,
baseDirectory: 'outputs/lza-config',
},
localConfig: {
baseDirectory: 'outputs/lza-config',
},
region: config.homeRegion,
};
this.writeToSources = new WriteToSources(this.writeFilesConfig);
}
async process() {
const aseaConfig = await loadAseaConfig({
filePath: 'raw/config.json',
repositoryName: this.aseaConfigRepositoryName,
defaultRegion: this.region,
localFilePath: this.localConfigFilePath,
});
this.accounts = await loadAccounts(this.parametersTable, this.dynamoDb);
this.vpcAssignedCidrs = await loadVpcAssignedCidrs(vpcCidrsTableName(this.aseaPrefix), this.dynamoDb);
this.subnetAssignedCidrs = await loadSubnetAssignedCidrs(subnetsCidrsTableName(this.aseaPrefix), this.dynamoDb);
this.outputs = await loadOutputs(`${this.aseaPrefix}Outputs`, this.dynamoDb);
this.globalOptions = aseaConfig['global-options'];
this.vpcConfigs = aseaConfig.getVpcConfigs();
const regionsWithVpc = this.vpcConfigs.map((resolvedConfig) => resolvedConfig.vpcConfig.region);
this.regionsWithoutVpc = this.globalOptions['supported-regions'].filter(
(region) => !regionsWithVpc.includes(region),
);
const accountKeys = aseaConfig.getAccountConfigs().map(([accountKey]) => accountKey);
this.accountsWithVpc = new Set<string>();
//this.albTemplates = aseaConfig.getAlbTemplateConfigs();
/**
* Loop VPC Configs and get accounts and regions with VPC
* Compute accounts and regions with out VPC to exclude for EBS Default Encryption and sessionManager configuration.
*/
for (const { ouKey, vpcConfig, accountKey, excludeAccounts } of this.vpcConfigs) {
if (!!accountKey) {
this.accountsWithVpc.add(accountKey);
} else {
aseaConfig
.getAccountConfigsForOu(ouKey)
.map(([account]) => account)
.forEach((account) => this.accountsWithVpc.add(account));
}
for (const subnetConfig of vpcConfig.subnets ?? []) {
if (subnetConfig['share-to-ou-accounts']) {
aseaConfig
.getAccountConfigsForOu(ouKey)
.filter(([account]) => !excludeAccounts?.includes(account))
.map(([account]) => account)
.forEach((account) => this.accountsWithVpc.add(account));
}
if (!!subnetConfig['share-to-specific-accounts']) {
subnetConfig['share-to-specific-accounts'].forEach((account) => this.accountsWithVpc.add(account));
}
}
}
this.accountsWithoutVpc = accountKeys
.filter((accountKey) => !this.accountsWithVpc.has(accountKey))
.map((accountKey) => this.getAccountKeyforLza(this.globalOptions!, accountKey));
if (this.accountsWithVpc.has('management')) {
this.accountsWithVpc.delete('management');
this.accountsWithVpc.add('Management');
}
const index = this.accountsWithoutVpc.findIndex((x) => x === 'management');
if (index) {
this.accountsWithoutVpc[index] = 'Management';
}
await this.copyAdditionalAssets();
await this.configCheck.checkUnsupportedConfig(aseaConfig);
await this.prepareOrganizationConfig(aseaConfig);
await this.prepareIamConfig(aseaConfig);
await this.prepareGlobalConfig(aseaConfig);
this.lzaAccountKeys = await this.prepareAccountConfig(aseaConfig);
await this.prepareSecurityConfig(aseaConfig);
await this.prepareNetworkConfig(aseaConfig);
await this.prepareCustomizationsConfig(aseaConfig);
await this.createDynamicPartitioningFile(aseaConfig);
this.configCheck.printWarnings();
this.configCheck.printErrors();
}
/**
* Copy additional assets which are required for LZA
*/
private async copyAdditionalAssets() {
const filesToWrite = [];
filesToWrite.push(...this.generatePutFiles(Object.values(ConfigRuleRemediationAssets), LZA_CONFIG_RULES));
filesToWrite.push(...this.generatePutFiles(Object.values(ConfigRuleDetectionAssets), LZA_CONFIG_RULES));
filesToWrite.push(...this.generatePutFiles(Object.values(CloudFormationAssets), LZA_CLOUDFORMATION));
await this.writeToSources.writeFiles(filesToWrite);
}
private generatePutFiles(fileNames: string[], directory: string): WriteToSourcesTypes.PutFiles[] {
return fileNames.map((dir) => {
const fileNameArr = path.normalize(dir).split(path.sep);
const fileName = fileNameArr.pop()!;
const relativePath = fileNameArr.pop()!;
const content = fs.readFileSync(path.join(__dirname, 'assets', relativePath, fileName)).toString();
return {
fileContent: content,
filePath: directory,
fileName,
};
});
}
private getAccountKeyforLza(globalOptions: GlobalOptionsConfig, accountKey: string) {
switch (accountKey) {
case globalOptions['central-log-services'].account:
return AccountsConfig.LOG_ARCHIVE_ACCOUNT;
case globalOptions['central-security-services'].account:
return AccountsConfig.AUDIT_ACCOUNT;
case globalOptions['aws-org-management'].account:
return AccountsConfig.MANAGEMENT_ACCOUNT;
default:
return accountKey.replaceAll(' ', '');
}
}
private getCentralNetworkAccount() {
const centralResolvedVpcConfig = this.vpcConfigs.find(({ vpcConfig }) => vpcConfig['central-endpoint']);
return centralResolvedVpcConfig?.accountKey;
}
/**
* Transform rule variables to conform with LZA types.
* @param ruleGroup
* @returns
*/
private transformRuleVariables(ruleGroup: any) {
const ruleVariables = ruleGroup.ruleVariables;
if (!ruleVariables) return;
const ipSets: { name: string; definition: string[] }[] = [];
const portSets: { name: string; definition: string[] }[] = [];
for (const [name, definition] of Object.entries(ruleVariables.ipSets ?? {})) {
ipSets.push({
name,
definition: (definition as { definition: string[] }).definition,
});
}
for (const [name, definition] of Object.entries(ruleVariables.portSets ?? {})) {
portSets.push({
name,
definition: (definition as { definition: string[] }).definition,
});
}
return {
ipSets,
portSets,
};
}
/**
* Transform ruleOptions to conform with LZA types.
* @param ruleGroup
* @returns
*/
private transformRuleOptions(ruleGroup: any) {
if (!ruleGroup.statefulRuleOptions) return;
return ruleGroup.statefulRuleOptions.ruleOrder;
}
/**
* Transform stateless and custom rule group policies to conform with LZA types.
* @param ruleGroup
*/
private transformStatelessCustom(ruleSource: any) {
const property = ruleSource.statelessRulesAndCustomActions;
if (!property) return;
const statelessRules: NfwRuleSourceStatelessRuleConfig[] = [];
const customActions: NfwRuleSourceCustomActionConfig[] = [];
for (const rule of property.statelessRules ?? []) {
statelessRules.push({
priority: rule.priority,
ruleDefinition: {
actions: rule.ruleDefinition.actions,
matchAttributes: {
destinationPorts: rule.ruleDefinition.matchAttributes?.destinationPorts ?? [],
protocols: rule.ruleDefinition.matchAttributes?.protocols ?? [],
sourcePorts: rule.ruleDefinition.matchAttributes?.sourcePorts ?? [],
tcpFlags: rule.ruleDefinition.matchAttributes?.tcpFlags,
destinations: (rule.ruleDefinition.matchAttributes.destinations ?? []).map(
(destination: { addressDefinition: string }) => destination.addressDefinition,
),
sources: (rule.ruleDefinition.matchAttributes.sources ?? []).map(
(source: { addressDefinition: string }) => source.addressDefinition,
),
},
},
});
}
return {
statelessRules,
customActions,
};
}
/**
* NetworkFirewallConfig is prepared considering ASEA firewall names are unique across all accounts and regions.
* Default ASEA reference artifacts had only one firewall created.
* Works for multiple nfw with different names
*
* TODO: Add suffix to make NFW name unique
* @returns
*/
private async getNetworkFirewallConfig() {
const firewalls: NfwFirewallConfig[] = [];
const policies: NfwFirewallPolicyConfig[] = [];
const ruleGroups: NfwRuleGroupConfig[] = [];
const nfwVpcConfigs = this.vpcConfigs.filter((resolvedVpcConfig) => !!resolvedVpcConfig.vpcConfig.nfw);
for (const { vpcConfig, accountKey, lzaVpcName } of nfwVpcConfigs) {
const networkFirewallConfig = vpcConfig.nfw!;
const firewallConfigName = networkFirewallConfig['firewall-name'] || `${vpcConfig.name}-nfw`;
const policyName = createNetworkFirewallPolicyName(
networkFirewallConfig.policy?.name ?? 'Sample-Firewall-Policy',
firewallConfigName,
this.aseaPrefix,
);
const policyString =
networkFirewallConfig.policyString ??
(await this.s3.getObjectBodyAsString({
Bucket: this.centralBucketName,
Key: networkFirewallConfig.policy?.path ?? 'nfw/nfw-example-policy.json',
}));
const policyData = JSON.parse(policyString);
let statefulRuleGroups;
if (policyData.statefulRuleGroup) {
statefulRuleGroups = policyData.statefulRuleGroup.map((ruleGroup: any) => ({
name: createNetworkFirewallRuleGroupName(ruleGroup.ruleGroupName, firewallConfigName, this.aseaPrefix),
priority: ruleGroup.priority,
}));
} else {
statefulRuleGroups = undefined;
}
let statelessRuleGroups;
if (policyData.statelessRuleGroup) {
statelessRuleGroups = policyData.statelessRuleGroup.map((ruleGroup: any) => ({
name: createNetworkFirewallRuleGroupName(ruleGroup.ruleGroupName, firewallConfigName, this.aseaPrefix),
priority: ruleGroup.priority,
}));
} else {
statelessRuleGroups = undefined;
}
policies.push({
name: policyName,
regions: [vpcConfig.region],
description: undefined,
shareTargets: {
accounts: [this.getAccountKeyforLza(this.globalOptions!, accountKey!)],
organizationalUnits: [],
},
tags: [],
firewallPolicy: {
statefulDefaultActions: policyData.statefulDefaultActions,
statefulEngineOptions: policyData.statefulEngineOptions,
statelessDefaultActions: policyData.statelessDefaultActions,
statelessFragmentDefaultActions: policyData.statelessFragmentDefaultActions,
statelessCustomActions: policyData.statelessCustomActions,
statefulRuleGroups: statefulRuleGroups,
statelessRuleGroups: statelessRuleGroups,
},
});
[...policyData.statefulRuleGroup ?? [], ...policyData.statelessRuleGroup ?? [] ].forEach((ruleGroup: any) => {
ruleGroups.push({
capacity: ruleGroup.capacity,
description: undefined,
name: createNetworkFirewallRuleGroupName(ruleGroup.ruleGroupName, firewallConfigName, this.aseaPrefix),
type: ruleGroup.type,
regions: [vpcConfig.region],
shareTargets: {
accounts: [this.getAccountKeyforLza(this.globalOptions!, accountKey!)],
organizationalUnits: [],
},
tags: [],
ruleGroup: {
rulesSource: {
rulesSourceList: ruleGroup.ruleGroup.rulesSource.rulesSourceList,
rulesFile: undefined,
rulesString: ruleGroup.ruleGroup.rulesSource.rulesString,
statefulRules: ruleGroup.ruleGroup.rulesSource.statefulRules,
statelessRulesAndCustomActions: this.transformStatelessCustom(ruleGroup.ruleGroup.rulesSource),
},
ruleVariables: this.transformRuleVariables(ruleGroup.ruleGroup),
statefulRuleOptions: this.transformRuleOptions(ruleGroup.ruleGroup),
},
});
});
const loggingConfiguration: NfwLoggingConfig[] = [];
if (networkFirewallConfig['alert-dest'] !== 'None') {
loggingConfiguration.push({
destination: networkFirewallConfig['alert-dest'] === 'CloudWatch' ? 'cloud-watch-logs' : 's3',
type: 'ALERT',
});
}
if (networkFirewallConfig['flow-dest'] !== 'None') {
loggingConfiguration.push({
destination: networkFirewallConfig['flow-dest'] === 'CloudWatch' ? 'cloud-watch-logs' : 's3',
type: 'FLOW',
});
}
firewalls.push({
deleteProtection: false,
description: undefined,
firewallPolicy: policyName,
firewallPolicyChangeProtection: false,
loggingConfiguration,
name: createNetworkFirewallName(firewallConfigName, this.aseaPrefix),
subnetChangeProtection: false,
tags: [],
vpc: createVpcName(lzaVpcName ?? vpcConfig.name),
subnets: this.getAzSubnets(vpcConfig, networkFirewallConfig.subnet.name).map((subnet) =>
createSubnetName(lzaVpcName ?? vpcConfig.name, subnet.subnetName, subnet.az),
),
});
}
return {
firewalls,
policies,
rules: ruleGroups,
};
}
private async prepareGlobalConfig(aseaConfig: AcceleratorConfig) {
const globalOptions = aseaConfig['global-options'];
const centralizeLogging = globalOptions['central-log-services'];
const costAndUsageReport = globalOptions.reports['cost-and-usage-report'];
const dynamicLogPartitioning = centralizeLogging['dynamic-s3-log-partitioning'];
const centralLogBucketOutput = findValuesFromOutputs({
outputs: this.outputs,
accountKey: this.globalOptions?.['central-log-services'].account,
region: this.region,
predicate: (o) => o.type === 'LogBucket',
})?.[0];
const centralLogBucket = centralLogBucketOutput.value.bucketName;
const centralLogBucketArn = centralLogBucketOutput.value.bucketArn;
const centralLogEncryptionKey = centralLogBucketOutput.value.encryptionKeyArn;
const logAccountId = getAccountId(
this.accounts,
this.globalOptions?.['central-log-services'].account ?? 'log-archive',
)!;
const logAccountCredentials = await this.sts.getCredentialsForAccountAndRole(
logAccountId,
this.assumeRoleName,
);
const s3 = new S3(logAccountCredentials, this.region);
const kms = new KMS(logAccountCredentials, this.region);
const centralLogBucketPolicy = await s3.getBucketPolicy({
Bucket: centralLogBucket,
});
// GuardDuty and Macie related permissions
if (
!centralLogBucketPolicy.Statement.find(
(policyStatement: { Sid: string }) => policyStatement.Sid === 'GuardDuty_Macie_Permissions',
)
) {
centralLogBucketPolicy.Statement.push({
Sid: 'GuardDuty_Macie_Permissions',
Effect: 'Allow',
Principal: {
Service: ['macie.amazonaws.com', 'guardduty.amazonaws.com'],
},
Action: [
's3:GetObject*',
's3:GetBucket*',
's3:List*',
's3:DeleteObject*',
's3:PutObject',
's3:PutObjectLegalHold',
's3:PutObjectRetention',
's3:PutObjectTagging',
's3:PutObjectVersionTagging',
's3:Abort*',
],
Resource: [centralLogBucketArn, `${centralLogBucketArn}/*`],
});
}
// Add GetEncryptionContext for GuardDuty and Macie
if (
!centralLogBucketPolicy.Statement.find(
(policyStatement: { Sid: string }) => policyStatement.Sid === 'GetEncryptionContext',
)
) {
centralLogBucketPolicy.Statement.push({
Sid: 'GetEncryptionContext',
Effect: 'Allow',
Principal: {
AWS: '*',
},
Action: ['s3:GetEncryptionConfiguration', 's3:GetBucketAcl'],
Resource: centralLogBucketArn,
Condition: {
StringEquals: {
'aws:PrincipalOrgID': '${ORG_ID}',
},
},
});
}
// Allow Organizations usage
if (
!centralLogBucketPolicy.Statement.find(
(policyStatement: { Sid: string }) => policyStatement.Sid === 'AllowOrganizationUsage',
)
) {
centralLogBucketPolicy.Statement.push({
Sid: 'AllowOrganizationUsage',
Effect: 'Allow',
Principal: {
AWS: '*',
},
Action: ['s3:GetBucketLocation', 's3:GetBucketAcl', 's3:PutObject', 's3:GetObject', 's3:ListBucket'],
Resource: [centralLogBucketArn, `${centralLogBucketArn}/*`],
Condition: {
StringEquals: {
'aws:PrincipalOrgID': '${ORG_ID}',
},
},
});
}
const centralLogBucketPolicyFile = posix.join(LZA_BUCKET_POLICY, 'central-log-bucket.json');
await this.writeToSources.writeFiles([
{
fileContent: JSON.stringify(centralLogBucketPolicy, null, 2),
fileName: 'central-log-bucket.json',
filePath: LZA_BUCKET_POLICY,
},
]);
const centralLogKeyPolicyFile = posix.join(LZA_KMS_POLICY, 'central-log-bucket-key.json');
const centralLogKeyPolicy = await kms.getKeyPolicy({
KeyId: centralLogEncryptionKey,
PolicyName: 'default',
});
if (
!centralLogKeyPolicy.Statement.find(
(policyStatement: { Sid: string }) => policyStatement.Sid === 'ConfigPermissions',
)
) {
centralLogKeyPolicy.Statement.push({
Sid: 'ConfigPermissions',
Effect: 'Allow',
Principal: {
Service: ['config.amazonaws.com'],
},
Action: ['kms:Encrypt', 'kms:Decrypt', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:DescribeKey'],
Resource: '*',
});
}
if (
!centralLogKeyPolicy.Statement.find(
(policyStatement: { Sid: string }) => policyStatement.Sid === 'GuardDuty_Macie_Permissions',
)
) {
centralLogKeyPolicy.Statement.push({
Sid: 'GuardDuty_Macie_Permissions',
Effect: 'Allow',
Principal: {
Service: ['macie.amazonaws.com', 'guardduty.amazonaws.com'],
},
Action: ['kms:Encrypt', 'kms:Decrypt', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:DescribeKey'],
Resource: '*',
});
}
await this.writeToSources.writeFiles([
{
fileContent: JSON.stringify(centralLogKeyPolicy, null, 2),
fileName: 'central-log-bucket-key.json',
filePath: LZA_KMS_POLICY,
},
]);
const ssmRoleNames: string[] = [];
aseaConfig.getAccountConfigs().forEach(([_accountKey, accountConfig]) => {
ssmRoleNames.push(
...(accountConfig.iam?.roles ?? [])
.filter(
(role) =>
role['ssm-log-archive-access'] ||
role['ssm-log-archive-read-only-access'] ||
role['ssm-log-archive-write-access'],
)
.map((role) => role.role),
);
});
aseaConfig.getOrganizationConfigs().forEach(([_ouKey, ouConfig]) => {
ssmRoleNames.push(
...(ouConfig.iam?.roles ?? [])
.filter(
(role) =>
role['ssm-log-archive-access'] ||
role['ssm-log-archive-read-only-access'] ||
role['ssm-log-archive-write-access'],
)
.map((role) => role.role),
);
});
// Create regions exclusion list for CMK
const excludeRegions: string[] = [];
for (const regionItem of globalOptions['supported-regions']) {
if (regionItem !== globalOptions['aws-org-management'].region) {
excludeRegions.push(regionItem);
}
}
const ousForS3EncryptionDeploymentTargetsWithoutNestedOus = Object.entries(aseaConfig['organizational-units']).map(
([ouName]) => ouName,
);
const ouForS3EncryptionDeploymentTargetsWithOus = this.getNestedOusForDeploymentTargets(
ousForS3EncryptionDeploymentTargetsWithoutNestedOus,
);
let cloudtrailConfig = undefined;
if (globalOptions['ct-baseline'] === true) {
cloudtrailConfig = {
enable: true,
organizationTrail: true,
organizationTrailSettings: {
multiRegionTrail: true,
globalServiceEvents: false,
managementEvents: false,
s3DataEvents: true,
lambdaDataEvents: false,
sendToCloudWatchLogs: true,
apiErrorRateInsight: false,
apiCallRateInsight: false,
}
}
} else {
cloudtrailConfig = {
enable: true,
organizationTrail: true,
organizationTrailSettings: {
multiRegionTrail: true,
globalServiceEvents: true,
managementEvents: true,
s3DataEvents: true,
lambdaDataEvents: false,
sendToCloudWatchLogs: true,
apiErrorRateInsight: false,
apiCallRateInsight: true,
}
}
}
const globalConfigAttributes: { [key: string]: unknown } = {
externalLandingZoneResources: {
importExternalLandingZoneResources: true,
acceleratorPrefix: this.aseaPrefix.replaceAll('-', ''),
acceleratorName: this.acceleratorName,
mappingFileBucket: this.mappingFileBucket,
},
homeRegion: this.region,
enabledRegions: globalOptions['supported-regions'],
managementAccountAccessRole: globalOptions['organization-admin-role'] || 'OrganizationAccountAccessRole',
cloudwatchLogRetentionInDays: LOG_RETENTION.includes(globalOptions['default-cwl-retention'])
? globalOptions['default-cwl-retention']
: 3653,
terminationProtection: this.enableTerminationProtection,
controlTower: { enable: globalOptions['ct-baseline'] },
cdkOptions: {
centralizeBuckets: true,
useManagementAccessRole: false,
customDeploymentRole: `${this.aseaPrefix}LZA-DeploymentRole`,
},
lambda: {
encryption: {
useCMK: false,
},
},
s3: {
encryption: {
createCMK: true,
deploymentTargets: {
accounts: ['Management'],
organizationalUnits: ouForS3EncryptionDeploymentTargetsWithOus,
excludedRegions: excludeRegions,
},
},
},
logging: {
account: this.getAccountKeyforLza(globalOptions, centralizeLogging.account),
centralizedLoggingRegion: centralizeLogging.region,
cloudtrail: cloudtrailConfig,
sessionManager: {
sendToS3: centralizeLogging['ssm-to-s3'],
sendToCloudWatchLogs: centralizeLogging['ssm-to-cwl'],
lifecycleRules: [
{
enabled: true,
abortIncompleteMultipartUpload: 7,
expiration: 730,
noncurrentVersionExpiration: 730,
},
],
attachPolicyToIamRoles: Array.from(new Set(ssmRoleNames)),
excludeRegions: this.regionsWithoutVpc,
excludeAccounts: this.accountsWithoutVpc,
},
// No option to customize on ASEA apart from expiration/retention
accessLogBucket: {
enable: false,
},
centralLogBucket: {
lifecycleRules: [
{
enabled: true,
abortIncompleteMultipartUpload: 7,
expiration: centralizeLogging['s3-retention'] ?? 730,
noncurrentVersionExpiration: centralizeLogging['s3-retention'] ?? 730,
},
],
importedBucket: {
name: centralLogBucket,
},
customPolicyOverrides: {
s3Policy: centralLogBucketPolicyFile,
kmsPolicy: centralLogKeyPolicyFile,
},
},
elbLogBucket: {
lifecycleRules: [
{
enabled: true,
abortIncompleteMultipartUpload: 7,
expiration: centralizeLogging['s3-retention'] ?? 730,
noncurrentVersionExpiration: centralizeLogging['s3-retention'] ?? 730,
},
],
// No example found for globalConfig.logging.centralLogBucket.s3ResourcePolicyAttachments in any of the configs
// TODO: Add to manual verification
// s3ResourcePolicyAttachments: [],
},
//
cloudwatchLogs: {
enable: true,
encryption: {
useCMK: true,
deploymentTargets: {
organizationalUnits: ['Root'],
excludedRegions: this.regionsWithoutVpc ?? undefined,
},
},
dynamicPartitioning: dynamicLogPartitioning ? 'dynamic-partitioning/log-filters.json' : undefined,
replaceLogDestinationArn: `arn:aws:logs:${this.region}:${logAccountId}:destination:${this.aseaPrefix}LogDestinationOrg`,
},
},
reports: {
costAndUsageReport: {
additionalSchemaElements: costAndUsageReport['additional-schema-elements'],
compression: costAndUsageReport.compression,
format: costAndUsageReport.format,
reportName: `${this.aseaPrefix}${costAndUsageReport['report-name']}`, // TODO: Remove aseaPrefix when we fix cost and usage report
s3Prefix: costAndUsageReport['s3-prefix'],
timeUnit: costAndUsageReport['time-unit'],
additionalArtifacts: costAndUsageReport['additional-artifacts'],
refreshClosedReports: costAndUsageReport['refresh-closed-reports'],
reportVersioning: costAndUsageReport['report-versioning'],
},
budgets: this.buildBudgets(aseaConfig),
},
// No backup vaults in ASEA
// TODO: Add to manual verification
// backup: { vaults: [] }
snsTopics: this.buildSnsTopics(aseaConfig),
limits: this.buildLimits(aseaConfig),
// No acceleratorMetadata in ASEA
// TODO: Add to manual verification
acceleratorMetadata: this.buildAcceleratorMetadata(aseaConfig),
ssmInventory: this.buildSsmInventory(aseaConfig),
};
const globalConfig = GlobalConfig.fromObject(globalConfigAttributes);
const yamlConfig = yaml.dump(globalConfig, { noRefs: true });
await this.writeToSources.writeFiles([{ fileContent: yamlConfig, fileName: GlobalConfig.FILENAME }]);
}
private getNestedOusForDeploymentTargets(ousWithoutNestedOus: string[]) {
let ouWithNestedOus = ousWithoutNestedOus;
for (const ouWithoutNestedOus of ousWithoutNestedOus) {
if (this.ouToNestedOuMap.has(ouWithoutNestedOus)) {
const nestedOusForOu = this.ouToNestedOuMap.get(ouWithoutNestedOus);
if (nestedOusForOu) {
const nestedOuSet = this.ouToNestedOuMap.get(ouWithoutNestedOus);
if (nestedOuSet) {
ouWithNestedOus = [...ouWithNestedOus, ...Array.from(nestedOuSet)];
}
}
}
}
return ouWithNestedOus;
}
private buildAcceleratorMetadata(aseaConfig: AcceleratorConfig) {
let loggingAccount;
const metadataCollection = aseaConfig['global-options']['meta-data-collection'];
if (!metadataCollection) {
return;
}
const readOnlyAccessRoleArns = this.getReadOnlyAccessRoleArns(aseaConfig);
if (this.globalOptions) {
loggingAccount = this.getAccountKeyforLza(
aseaConfig['global-options'],
this.globalOptions?.['central-log-services'].account,
);
}
return {
enable: true,
account: loggingAccount,
readOnlyAccessRoleArns,
};
}
private getReadOnlyAccessRoleArns(aseaConfig: AcceleratorConfig) {
const accountRoleArnsList: string[][] = [];
const orgRoleArnsList: string[][] = [];
// Iterate through all accounts and find roles with meta-data-read-only-access defined and generate arn.
aseaConfig.getAccountConfigs().forEach(([_accountKey, accountConfig]) => {
const roles = accountConfig.iam?.roles ?? [];
const filteredAccountRoles = roles.filter((role) => role['meta-data-read-only-access']);
const accountId = getAccountId(this.accounts, _accountKey);
accountRoleArnsList.push(filteredAccountRoles.map((role) => `arn:aws:iam:${accountId}:role/${role.role}`));
});
// Iterate through all orgs, look up accounts, and find roles with meta-data-read-only-access defined and generate arn.
aseaConfig.getOrganizationConfigs().forEach(([_ouKey, ouConfig]) => {
const roles = ouConfig.iam?.roles ?? [];
const filteredRoles = roles.filter((role) => role['meta-data-read-only-access']);
const organizationAccountIds = this.accounts
.filter((account) => account.ou === _ouKey)
.map((ouAccount) => ouAccount.id);
for (const organizationAccountId of organizationAccountIds) {
orgRoleArnsList.push(filteredRoles.map((role) => `arn:aws:iam:${organizationAccountId}:role/${role.role}`));
}
});
// Convert both account and org role arns lists to flat lists so its a single list rather than list of lists.
const accountRoleArns = accountRoleArnsList.flat();
const orgRoleArns = orgRoleArnsList.flat();
// Convert to set in-case role arn is created from both OU and account config
const readOnlyAccessRoleArnsSet = new Set([...accountRoleArns, ...orgRoleArns]);
const readOnlyAccessRoleArns = Array.from(readOnlyAccessRoleArnsSet);
return readOnlyAccessRoleArns;
}
private buildBudgets(aseaConfig: AcceleratorConfig) {
enum CostTypes {
CREDIT = 'Credits',
DISCOUNT = 'Discounts',
OTHER = 'Other-subscription-costs',
RECURRING = 'Recurring-reservation-charges',
REFUND = 'Refunds',
SUBSCRIPTION = 'Subscription',
SUPPORT = 'Support-charges',
TAX = 'Taxes',
UPFRONT = 'Upfront-reservation-fees',
AMORTIZED = 'Amortized',
BLENDED = 'Blended',
}
const budgets: unknown[] = [];
const budgetCreatedToAccounts: string[] = [];
aseaConfig.getAccountConfigs().forEach(([accountKey, accountConfig]) => {
if (!accountConfig.budget) return;
const budget = accountConfig.budget;
budgets.push({
name: `${this.aseaPrefix}${budget.name}`,