-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.yaml
446 lines (428 loc) · 14.7 KB
/
template.yaml
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
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: This solution deploys a solution for converting CloudFront Realtime Logs into time-series metrics then processing the metrics to find offending IP's to block. It deploys an Amazon Kinesis Data Stream, AWS Lambda Function and Amazon Timestream Database, AWS Web Application Firewall, SNS Topic, Dynamo DB.
Parameters:
KinesisStreamShards:
Description: Number of shards to provision for the CloudFront Real Time Logs Kinesis Data Stream
Type: Number
Default: 1
RealtimeLogsSamplingPercentage:
Description: The sampling rate (expressed as integer or float value between 1-100) to use for the Real-time Logs Configuration. This value will be set in the Real-time Logs Configuration. Defaults to 5 (5%) sampling rate.
Type: Number
Default: 4
MinValue: 1
MaxValue: 100
EmailAddress:
Type: String
Description: "Email address to send Alerts of Blocked IP's"
Default: ''
Resources:
LogProcessor:
Type: AWS::Serverless::Function
Properties:
Handler: lambda_function.lambda_handler
Runtime: python3.8
CodeUri: ./log-processor
Description: An Amazon Kinesis stream processor to process real-time logs from Amazon CloudFront and convert to CW Metrics
MemorySize: 128
Timeout: 60
Events:
KinesisEvent:
Type: Kinesis
Properties:
Stream: !GetAtt CloudFrontLogStream.Arn
StartingPosition: LATEST
BatchSize: 1000
MaximumBatchingWindowInSeconds: 10
Enabled: true
Environment:
Variables:
TABLE_NAME: !Ref RealtimeLogsTable
HOST_FN_NAME: !Ref HostProcessor
Policies:
- Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- kinesis:Get*
- kinesis:List*
- kinesis:Describe*
Resource: !GetAtt CloudFrontLogStream.Arn
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutDestination
- logs:PutLogEvents
Resource:
- !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*'
- Effect: Allow
Action:
- xray:PutTraceSegments
- xray:PutTelemetryRecords
- xray:GetSamplingRules
- xray:GetSamplingTargets
Resource:
- '*'
- Effect: Allow
Action:
- timestream:WriteRecords
Resource:
- !Sub '${CloudFrontLogsTimeSeriesDb.Arn}/table/*'
- Effect: Allow
Action:
- timestream:DescribeEndpoints
Resource:
- '*'
- Effect: Allow
Action:
- lambda:InvokeFunction
Resource:
- !Sub 'arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:*'
CustomResourceHelper:
Type: AWS::Serverless::Function
Properties:
Handler: lambda_function.lambda_handler
Runtime: python3.8
CodeUri: ./custom-resource
Description: Custom Resource function to assist with CloudFormation deployment process
MemorySize: 128
Timeout: 60
Policies:
- Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutDestination
- logs:PutLogEvents
Resource:
- !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*'
- Effect: Allow
Action:
- xray:PutTraceSegments
- xray:PutTelemetryRecords
- xray:GetSamplingRules
- xray:GetSamplingTargets
Resource:
- '*'
HostProcessor:
Type: AWS::Serverless::Function
Properties:
Handler: host_processor.lambda_handler
Runtime: python3.8
CodeUri: ./HostProcessor
FunctionName: HostProcessor
Description: Lambda to Query TimestreamDB and Block IP when reached threshold
MemorySize: 512
Timeout: 60
Environment:
Variables:
LOG_LVL: '20'
SNS_ARN: !Ref SNSWAFIpBlockNotifiaction
THREAD_COUNT: 2
CONFIGURATION_DYNAMODB: !Ref WAFConfigTable
BLOCKLIST_DYNAMODB: !Ref WAFBlockHistoryTable
TIMESTREAM_DB_NAME: !Ref CloudFrontLogsTimeSeriesDb
TIMESTREAM_TABLE_NAME: !GetAtt RealtimeLogsTable.Name
IPV4SET_DETAILS: !Ref WAFIpSetIpV4
IPV6SET_DETAILS: !Ref WAFIpSetIpV6
Policies:
- Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- sns:Publish
Resource:
- !Ref SNSWAFIpBlockNotifiaction
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutDestination
- logs:PutLogEvents
Resource:
- !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*'
- Effect: Allow
Action:
- xray:PutTraceSegments
- xray:PutTelemetryRecords
- xray:GetSamplingRules
- xray:GetSamplingTargets
Resource:
- '*'
- Effect: Allow
Action:
- timestream:DescribeEndpoints
Resource:
- '*'
- Effect: Allow
Action:
- timestream:Select
Resource:
- !Sub 'arn:${AWS::Partition}:timestream:${AWS::Region}:${AWS::AccountId}:database/${CloudFrontLogsTimeSeriesDb}/table/${RealtimeLogsTable.Name}'
- Effect: Allow
Action:
- wafv2:GetIPSet
- wafv2:UpdateIPSet
Resource:
- !Sub 'arn:${AWS::Partition}:wafv2:${AWS::Region}:${AWS::AccountId}:global/ipset/*/${WAFIpSetIpV4.Id}'
- !Sub 'arn:${AWS::Partition}:wafv2:${AWS::Region}:${AWS::AccountId}:global/ipset/*/${WAFIpSetIpV6.Id}'
- Effect: Allow
Action:
- dynamodb:GetItem
Resource:
- !Sub 'arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${WAFConfigTable}'
- Effect: Allow
Action:
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:BatchWriteItem
Resource:
- !Sub 'arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${WAFBlockHistoryTable}'
WAFConfigTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: distribution
AttributeType: S
- AttributeName: host
AttributeType: S
KeySchema:
- AttributeName: distribution
KeyType: HASH
- AttributeName: host
KeyType: RANGE
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 1
TableName: "waf-config"
WAFBlockHistoryTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: distribution
AttributeType: S
- AttributeName: ip
AttributeType: S
KeySchema:
- AttributeName: distribution
KeyType: HASH
- AttributeName: ip
KeyType: RANGE
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 1
TableName: "waf-block-ip-history"
CloudFrontRealtimeLogConfig:
Type: AWS::CloudFront::RealtimeLogConfig
Properties:
Name: !Sub 'CloudFrontRealTimeLogConfig-${AWS::StackName}'
SamplingRate: !Ref RealtimeLogsSamplingPercentage
EndPoints:
- KinesisStreamConfig:
RoleArn: !GetAtt CloudFrontRealTimeLogsConfigRole.Arn
StreamArn: !GetAtt CloudFrontLogStream.Arn
StreamType: Kinesis
Fields:
- timestamp
- c-ip
- time-to-first-byte
- sc-status
- sc-bytes
- cs-method
- cs-protocol
- cs-host
- cs-uri-stem
- cs-bytes
- x-edge-location
- x-edge-request-id
- x-host-header
- time-taken
- cs-protocol-version
- c-ip-version
- cs-user-agent
- cs-referer
- cs-cookie
- cs-uri-query
- x-edge-response-result-type
- x-forwarded-for
- ssl-protocol
- ssl-cipher
- x-edge-result-type
- fle-encrypted-fields
- fle-status
- sc-content-type
- sc-content-len
- sc-range-start
- sc-range-end
- c-port
- x-edge-detailed-result-type
- c-country
- cs-accept-encoding
- cs-accept
- cache-behavior-path-pattern
- cs-headers
- cs-header-names
- cs-headers-count
# IAM Role for CloudFront to deliver real-time logs to Kinesis Data Stream
CloudFrontRealTimeLogsConfigRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- cloudfront.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: root
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- kinesis:PutRecord
- kinesis:PutRecords
- kinesis:DescribeStreamSummary
- kinesis:DescribeStream
Resource:
- !GetAtt CloudFrontLogStream.Arn
LogProcessorLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${LogProcessor}'
RetentionInDays: 30
HostProcessorLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${HostProcessor}'
RetentionInDays: 30
CloudFrontLogStream:
Type: AWS::Kinesis::Stream
Properties:
ShardCount: !Ref KinesisStreamShards
StreamEncryption:
EncryptionType: KMS
KeyId: alias/aws/kinesis
CloudFrontLogsTimeSeriesDb:
Type: AWS::Timestream::Database
RealtimeLogsTable:
Type: AWS::Timestream::Table
Properties:
DatabaseName: !Ref CloudFrontLogsTimeSeriesDb
RetentionProperties:
MemoryStoreRetentionPeriodInHours: 7
MagneticStoreRetentionPeriodInDays: 1
SNSWAFIpBlockNotifiaction:
Type: AWS::SNS::Topic
Properties:
DisplayName: "Waf-Ip-Block-Notification"
Subscription:
- Endpoint: !Ref EmailAddress
Protocol: 'email'
# WAF Resources, Will only work in region us-east-1
WAFIpSetIpV4:
Type: 'AWS::WAFv2::IPSet'
Properties:
Description: CloudFront blocked IpV4 addresses
Name: IPV4SET
Scope: CLOUDFRONT
IPAddressVersion: IPV4
Addresses:
- 10.0.0.0/32 # A dummy IPV4 Private Ip
WAFIpSetIpV6:
Type: 'AWS::WAFv2::IPSet'
Properties:
Description: CloudFront blocked IpV6 addresses
Name: IPV6SET
Scope: CLOUDFRONT
IPAddressVersion: IPV6
Addresses:
- fd4b:9821:be17:8c1e:0000:0000:0000:0000/128 # A dummy IPV6 Private Ip
WAFWebACL:
DependsOn:
- WAFIpSetIpV4
- WAFIpSetIpV6
Type: 'AWS::WAFv2::WebACL'
Properties:
Name: WebACL-Cloudfront
Scope: CLOUDFRONT
Description: Blocks IP When requests are greater than threshold
DefaultAction:
Allow: {} # allow all
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: WebACLMetricForCloudfront
Rules:
- Name: SourceIPv4
Priority: 0
Statement:
IPSetReferenceStatement:
Arn: !GetAtt WAFIpSetIpV4.Arn
Action:
Block: {} # Block all
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: SourceIPv4
- Name: XXFIPv4
Priority: 1
Statement:
IPSetReferenceStatement:
Arn: !GetAtt WAFIpSetIpV4.Arn
IPSetForwardedIPConfig:
HeaderName: x-forwarded-for
FallbackBehavior: MATCH
Position: ANY
Action:
Block: {}
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: XXFIPv4
- Name: SourceIPv6
Priority: 2
Statement:
IPSetReferenceStatement:
Arn: !GetAtt WAFIpSetIpV6.Arn
Action:
Block: {}
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: SourceIPv6
- Name: XFFIPv6
Priority: 3
Statement:
IPSetReferenceStatement:
Arn: !GetAtt WAFIpSetIpV6.Arn
IPSetForwardedIPConfig:
HeaderName: x-forwarded-for
FallbackBehavior: MATCH
Position: ANY
Action:
Block: {}
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: XFFIPv6
Outputs:
CloudWatchMetricsUrl:
Description: Link to the Amazon CloudWatch namespace where the custom metrics are published by the solution.
Value: !Sub 'https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#metricsV2:graph=~();query=${AWS::StackName}'
LogProcessorLogGroup:
Description: Link to the CloudWatch Log Group for the log processor lambda function where logs are delivered
Value: !Sub 'https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#logsV2:log-groups/log-group/$252Faws$252Flambda$252F${LogProcessor}'
HostProcessorLogGroup:
Description: Link to the CloudWatch Log Group for the host processor lambda function where logs are delivered
Value: !Sub 'https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#logsV2:log-groups/log-group/$252Faws$252Flambda$252F${HostProcessor}'
TimestreamQueryEditor:
Description: Link to the Amazon Timestream query editor for the database that was deployed by the solution
Value: !Sub 'https://console.aws.amazon.com/timestream/home?region=${AWS::Region}#query-editor:/Database/${CloudFrontLogsTimeSeriesDb}'