-
Notifications
You must be signed in to change notification settings - Fork 22
/
policy.stack.ts
671 lines (625 loc) · 21.4 KB
/
policy.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/**
* @description
* This is Policy Stack for Automations for AWS Firewall Manager
* The stack should be deployed in Firewall Manager admin account
* This stack provisions resources needed to manage FMS policies
* @author @aws-solutions
*/
import {
Stack,
CfnMapping,
RemovalPolicy,
Duration,
NestedStack,
CfnOutput,
CfnResource,
CfnParameter,
NestedStackProps,
CfnCondition,
Fn,
} from "aws-cdk-lib";
import { Construct } from "constructs";
import { StringListParameter, StringParameter } from "aws-cdk-lib/aws-ssm";
import { Queue, QueueEncryption, QueuePolicy } from "aws-cdk-lib/aws-sqs";
import { Code, Function, CfnFunction, Tracing } from "aws-cdk-lib/aws-lambda";
import {
LogGroup,
RetentionDays,
QueryDefinition,
QueryString,
} from "aws-cdk-lib/aws-logs";
import * as path from "path";
import {
BlockPublicAccess,
Bucket,
BucketEncryption,
StorageClass,
} from "aws-cdk-lib/aws-s3";
import {
AwsCustomResource,
AwsCustomResourcePolicy,
PhysicalResourceId,
} from "aws-cdk-lib/custom-resources";
import {
AnyPrincipal,
CfnPolicy,
Effect,
Policy,
PolicyStatement,
} from "aws-cdk-lib/aws-iam";
import { IAMConstruct } from "../common/iam.construct";
import manifest from "../solution_manifest.json";
import { LAMBDA_RUNTIME_NODE, LOG_LEVEL } from "../common/exports";
import { EventbridgeToLambda } from "@aws-solutions-constructs/aws-eventbridge-lambda";
import { Layer } from "../common/lambda-layer.construct";
import { CfnSubscription, Topic, TracingConfig } from "aws-cdk-lib/aws-sns";
import { Alias } from "aws-cdk-lib/aws-kms";
import { EmailSubscription } from "aws-cdk-lib/aws-sns-subscriptions";
export class PolicyStack extends NestedStack {
/**
* stack deployment AWS account
*/
readonly account: string;
/**
* stack deployment region
*/
readonly region: string;
constructor(scope: Construct, id: string, props: NestedStackProps) {
super(scope, id, props);
const stack = Stack.of(this);
this.account = stack.account; // Returns the AWS::AccountId for this stack (or the literal value if known)
this.region = stack.region; // Returns the AWS::Region for this stack (or the literal value if known)
//=============================================================================================
// Parameters
//=============================================================================================
const table = new CfnParameter(this, "PolicyTable", {
description: "DynamoDB table for policy metadata",
type: "String",
});
const uuid = new CfnParameter(this, "UUID", {
description: "UUID for primary stack deployment",
type: "String",
});
const policyIdentifier = new CfnParameter(this, "PolicyIdentifier", {
description: "A unique string identifier for the policies",
type: "String",
});
const emailAddress = new CfnParameter(this, "EmailAddress", {
type: "String",
description:
"Email address to receive notifications regarding problems deploying Firewall Manager policies.",
});
//=============================================================================================
// Metadata
//=============================================================================================
this.templateOptions.metadata = {
"AWS::CloudFormation::Interface": {
ParameterGroups: [
{
Label: { default: "Policy Configuration" },
Parameters: [policyIdentifier.logicalId, emailAddress.logicalId],
},
{
Label: { default: "Shared Resource Configurations" },
Parameters: [table.logicalId, uuid.logicalId],
},
],
ParameterLabels: {
[table.logicalId]: {
default: "Policy Table",
},
[uuid.logicalId]: {
default: "UUID",
},
[policyIdentifier.logicalId]: {
default: "Policy Identifier",
},
[emailAddress.logicalId]: {
default: "SNS Topic Email Address",
},
},
},
};
this.templateOptions.description = `(${manifest.solution.primarySolutionId}-po) - The AWS CloudFormation template for deployment of the ${manifest.solution.name}. Version ${manifest.solution.solutionVersion}`;
this.templateOptions.templateFormatVersion =
manifest.solution.templateVersion;
//=============================================================================================
// Map
//=============================================================================================
const map = new CfnMapping(this, "PolicyStackMap", {
mapping: {
Metric: {
SendAnonymizedMetric: manifest.solution.sendMetric,
MetricsEndpoint: manifest.solution.metricsEndpoint, // aws-solutions metrics endpoint
},
Solution: {
SolutionId: manifest.solution.primarySolutionId,
SolutionVersion: manifest.solution.solutionVersion,
UserAgentPrefix: manifest.solution.userAgentPrefix,
},
PolicyManager: {
ServiceName: manifest.policyStack.serviceName,
SNSTopicName: manifest.policyStack.SNSTopicName,
},
},
});
//=============================================================================================
// Condition
//=============================================================================================
const emailAddressExists = new CfnCondition(this, "emailAddressExists", {
expression: Fn.conditionNot(
Fn.conditionEquals(emailAddress.valueAsString, "")
),
});
//=============================================================================================
// Resources
//=============================================================================================
/**
* @description utility layer for common microservice code
*/
const utilsLayer = new Layer(
this,
"AFM-UtilsLayer",
`${path.dirname(__dirname)}/../../services/utilsLayer/dist/utilsLayer.zip`
);
/**
* @description - ssm parameter for org units
* @type {StringListParameter}
*/
const ou: StringListParameter = new StringListParameter(this, "FMSOUs", {
description: "FMS parameter store for OUs",
stringListValue: ["NOP"],
parameterName: `/FMS/${policyIdentifier.valueAsString}/OUs`,
simpleName: false,
});
/**
* @description ssm parameter for tags
* @type {StringParameter}
*/
const tags: StringParameter = new StringParameter(this, "FMSTags", {
description: "fms parameter for fms tags",
parameterName: `/FMS/${policyIdentifier.valueAsString}/Tags`,
stringValue: "NOP",
simpleName: false,
});
/**
* @description ssm parameter for regions
* @type {StringListParameter}
*/
const regions: StringListParameter = new StringListParameter(
this,
"FMSRegions",
{
description: "fms parameter for fms regions",
parameterName: `/FMS/${policyIdentifier.valueAsString}/Regions`,
stringListValue: ["NOP"],
simpleName: false,
}
);
/**
* @description S3 bucket for access logs
* @type {Bucket}
*/
const accessLogsBucket: Bucket = new Bucket(this, "AccessLogsBucket", {
versioned: true,
encryption: BucketEncryption.S3_MANAGED,
blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
lifecycleRules: [
{
transitions: [
{
storageClass: StorageClass.INFREQUENT_ACCESS,
transitionAfter: Duration.days(30),
},
{
storageClass: StorageClass.GLACIER,
transitionAfter: Duration.days(90),
},
],
expiration: Duration.days(365 * 2), // expire after 2 years
},
],
});
/**
* @description S3 bucket with default policy manifest
* @type {Bucket}
*/
const policyBucket: Bucket = new Bucket(this, "ManifestBucket", {
versioned: true,
encryption: BucketEncryption.S3_MANAGED,
blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
serverAccessLogsBucket: accessLogsBucket,
enforceSSL: true,
eventBridgeEnabled: true,
});
/**
* @description following snippet can be used to source policy manifest from local file
* @link https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-deployment-readme.html
* @example
```
new BucketDeployment(this, "CopyManifest", {
sources: [
Source.asset(`${path.dirname(__dirname)}/lib`, {
exclude: ["**", "!policy_manifest.json"],
}),
],
destinationBucket: policyBucket,
prune: true,
});
```
*/
new AwsCustomResource(this, "CopyManifest", {
onCreate: {
service: "S3",
action: "copyObject",
parameters: {
Bucket: policyBucket.bucketName,
CopySource: `${manifest.solution.policyBucket}-${this.region}/${manifest.solution.name}/${manifest.solution.solutionVersion}/policy_manifest.json`,
Key: "policy_manifest.json",
},
physicalResourceId: PhysicalResourceId.of(Date.now().toString()),
},
installLatestAwsSdk: false,
policy: AwsCustomResourcePolicy.fromStatements([
new PolicyStatement({
effect: Effect.ALLOW,
sid: "S3Get",
actions: ["s3:GetObject"],
resources: [
`arn:${stack.partition}:s3:::${manifest.solution.policyBucket}-${this.region}/*`,
],
}),
new PolicyStatement({
effect: Effect.ALLOW,
sid: "S3Put",
actions: ["s3:PutObject"],
resources: [`${policyBucket.bucketArn}/*`],
}),
]),
});
/**
* @description dead letter queue for lambda
* @type {Queue}
*/
const dlq: Queue = new Queue(this, `DLQ`, {
encryption: QueueEncryption.KMS_MANAGED,
});
/**
* @description SQS queue policy to enforce only encrypted connections over HTTPS,
* adding aws:SecureTransport in conditions
* @type {QueuePolicy}
*/
const queuePolicy: QueuePolicy = new QueuePolicy(this, "QueuePolicy", {
queues: [dlq],
});
queuePolicy.document.addStatements(
new PolicyStatement({
sid: "AllowPublishThroughSSLOnly",
actions: ["sqs:*"],
effect: Effect.DENY,
resources: [],
conditions: {
["Bool"]: {
"aws:SecureTransport": "false",
},
},
principals: [new AnyPrincipal()],
})
);
/**
* @description SNS topic for communicating errors during Policy deployment
* @type {Topic}
*/
const policyManagerTopic: Topic = new Topic(this, "PolicyManagerTopic", {
displayName: "FMS Policy Manager Topic",
topicName: map.findInMap("PolicyManager", "SNSTopicName"),
masterKey: Alias.fromAliasName(this, "SNSKey", "alias/aws/sns"),
enforceSSL: true,
tracingConfig: TracingConfig.ACTIVE,
});
const emailSubscription = policyManagerTopic.addSubscription(
new EmailSubscription(emailAddress.valueAsString)
);
const rawEmailSubscription = emailSubscription.node
.defaultChild as CfnSubscription;
rawEmailSubscription.cfnOptions.condition = emailAddressExists;
/**
* @description lambda function to create FMS security policy
* @type {Function}
*/
const policyManager: Function = new Function(this, "PolicyManager", {
description: `${map.findInMap(
"Solution",
"SolutionId"
)} - Function to create/update/delete FMS security policies`,
runtime: LAMBDA_RUNTIME_NODE,
layers: [utilsLayer.layer],
code: Code.fromAsset(
`${path.dirname(
__dirname
)}/../../services/policyManager/dist/policyManager.zip`
),
handler: "index.handler",
deadLetterQueue: dlq,
retryAttempts: 0,
maxEventAge: Duration.minutes(15),
deadLetterQueueEnabled: true,
memorySize: 512,
tracing: Tracing.ACTIVE,
environment: {
FMS_OU: ou.parameterName,
FMS_TAG: tags.parameterName,
FMS_REGION: regions.parameterName,
SSM_PARAM_PREFIX: `/FMS/${policyIdentifier.valueAsString}`,
FMS_TABLE: table.valueAsString,
POLICY_MANIFEST: `${policyBucket.bucketName}|policy_manifest.json`, // manifest file to be used for policy configuration
POLICY_IDENTIFIER: policyIdentifier.valueAsString,
SEND_METRIC: map.findInMap("Metric", "SendAnonymizedMetric"),
LOG_LEVEL: LOG_LEVEL.INFO, //change as needed
SOLUTION_ID: map.findInMap("Solution", "SolutionId"),
SOLUTION_VERSION: map.findInMap("Solution", "SolutionVersion"),
SERVICE_NAME: map.findInMap("PolicyManager", "ServiceName"),
MAX_ATTEMPTS: "" + 10, // retry attempts for SDKs, increase if you see throttling errors
UUID: uuid.valueAsString,
METRICS_ENDPOINT: map.findInMap("Metric", "MetricsEndpoint"),
USER_AGENT_PREFIX: map.findInMap("Solution", "UserAgentPrefix"),
PARTITION: stack.partition,
TOPIC_ARN: policyManagerTopic.topicArn,
},
timeout: Duration.minutes(15),
});
new EventbridgeToLambda(this, "EventsRuleLambda", {
existingLambdaObj: policyManager,
eventRuleProps: {
eventPattern: {
source: ["aws.ssm"],
detailType: ["Parameter Store Change"],
resources: [
`${ou.parameterArn}`,
`${tags.parameterArn}`,
`${regions.parameterArn}`,
],
},
},
});
new EventbridgeToLambda(this, "EventsRuleS3Lambda", {
existingLambdaObj: policyManager,
eventRuleProps: {
eventPattern: {
detailType: ["Object Created"],
source: ["aws.s3"],
resources: [policyBucket.bucketArn],
detail: {
bucket: {
name: [policyBucket.bucketName],
},
object: {
key: ["policy_manifest.json"],
},
},
},
},
});
// Add dependency between policy and notifications, so they aren't applied at the same time.
// Fixes race condition which causes failure to create Bucket Policy intermittently.
policyBucket.node
.findChild("Notifications")
.node.addDependency(policyBucket.node.findChild("Policy"));
/**
* @description log group for policy manager lambda function
* @type {LogGroup}
*/
const lg: LogGroup = new LogGroup(this, "PolicyMangerLogGroup", {
logGroupName: `/aws/lambda/${policyManager.functionName}`,
removalPolicy: RemovalPolicy.DESTROY,
retention: RetentionDays.TEN_YEARS,
});
/**
* @description iam permissions for the policy manager lambda function
* @type {IAMConstruct}
*/
new IAMConstruct(this, "LambdaIAM", {
policyTable: table.valueAsString,
sqs: dlq.queueArn,
logGroup: lg.logGroupArn,
role: policyManager.role!,
accountId: this.account,
region: this.region,
regionParamArn: regions.parameterArn,
ouParamArn: ou.parameterArn,
tagParamArn: tags.parameterArn,
s3Bucket: policyBucket,
policyIdentifier: policyIdentifier.valueAsString,
});
/**
* @description iam permissions for the policy lambda function
* to access X-ray
* @type {Policy}
*/
const policyManagerIAMPolicy: Policy = new Policy(
this,
"PolicyManagerIAMPolicy",
{
roles: [policyManager.role!],
}
);
/**
* @description iam policy statement with x-ray permissions
* @type {PolicyStatement}
*/
const xrayStatement: PolicyStatement = new PolicyStatement({
effect: Effect.ALLOW,
sid: "XRayWriteAccess",
actions: [
"xray:PutTraceSegments",
"xray:PutTelemetryRecords",
"xray:GetSamplingRules",
"xray:GetSamplingTargets",
"xray:GetSamplingStatisticSummaries",
],
resources: ["*"],
});
policyManagerIAMPolicy.addStatements(xrayStatement);
/**
* @description IAM permissions for writing to Policy Manager SNS topic
* @type {PolicyStatement}
*/
const SNSWriteStatement: PolicyStatement = new PolicyStatement({
effect: Effect.ALLOW,
sid: "SNSWrite",
actions: ["sns:Publish"],
resources: [policyManagerTopic.topicArn],
});
policyManagerIAMPolicy.addStatements(SNSWriteStatement);
//=============================================================================================
// Log Insights Queries
//=============================================================================================
const policyErrorQuery = new QueryDefinition(
this,
"PolicyManagerErrorQuery",
{
queryDefinitionName: "FMS-Policy_Manager_Errors",
logGroups: [lg],
queryString: new QueryString({
fields: ["@timestamp", "@level"],
sort: "@timestamp desc",
filterStatements: ['level = "ERROR"'],
}),
}
);
const policySuccessQuery = new QueryDefinition(
this,
"PolicyManagerSuccessQuery",
{
queryDefinitionName: "FMS-Policy_Manager_Success",
logGroups: [lg],
queryString: new QueryString({
fields: ["@timestamp", "@message"],
sort: "@timestamp desc",
filterStatements: ['message like "successfully put policy"'],
}),
}
);
const policyCreateFailureQuery = new QueryDefinition(
this,
"PolicyManagerCreateFailureQuery",
{
queryDefinitionName: "FMS-Policy_Manager_Create_Failure",
logGroups: [lg],
queryString: new QueryString({
fields: ["@timestamp", "@message"],
sort: "@timestamp desc",
filterStatements: ['message like "encountered error putting policy"'],
}),
}
);
//=============================================================================================
// cfn_nag suppress rules
//=============================================================================================
const cfn_nag_w58_w89_w92 = [
{
id: "W58",
reason:
"CloudWatch logs write permissions added with managed role AWSLambdaBasicExecutionRole",
},
{
id: "W89",
reason:
"Not a valid use case for Lambda functions to be deployed inside a VPC",
},
{
id: "W92",
reason: "Lambda ReservedConcurrentExecutions not needed",
},
];
(lg.node.findChild("Resource") as CfnResource).cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [
{
id: "W84",
reason:
"Using service default encryption https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/data-protection.html",
},
],
},
};
(
policyManager.node.findChild("Resource") as CfnFunction
).cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [...cfn_nag_w58_w89_w92],
},
};
(accessLogsBucket.node.defaultChild as CfnResource).cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [
{
id: "W35",
reason: "access logging disabled, its a logging bucket",
},
{
id: "W51",
reason: "permission given for log delivery",
},
],
},
guard: {
SuppressedRules: ["S3_BUCKET_NO_PUBLIC_RW_ACL"],
Reason: "Public RW access is disabled by default",
},
};
(policyBucket.node.defaultChild as CfnResource).cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [
{
id: "W51",
reason: "permission given to lambda to get policy manifest",
},
],
},
guard: {
SuppressedRules: ["S3_BUCKET_NO_PUBLIC_RW_ACL"],
Reason: "Public RW access is disabled by default",
},
};
(
policyManagerIAMPolicy.node.findChild("Resource") as CfnPolicy
).cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [
{
id: "W12",
reason:
"Resource * is required for function to write traces to X-Ray",
},
],
},
};
//=============================================================================================
// Output
//=============================================================================================
new CfnOutput(this, "Policy Manifest Bucket", {
description: "S3 Bucket with policy manifest file",
value: `s3://${policyBucket.bucketName}`,
});
new CfnOutput(this, "Policy Manager SNS Topic", {
description: "SNS Topic for Policy Manager notifications",
value: policyManagerTopic.topicName,
});
new CfnOutput(this, "Policy Manager Error Query", {
description: "Log Insights query for policy manager function errors",
value: policyErrorQuery.queryDefinitionId,
});
new CfnOutput(this, "Policy Manager Success Query", {
description: "Log Insights query for policy create successes",
value: policySuccessQuery.queryDefinitionId,
});
new CfnOutput(this, "Policy Manager Failure Query", {
description: "Log Insights query for policy create failures",
value: policyCreateFailureQuery.queryDefinitionId,
});
}
}