-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtemplate.yaml
1573 lines (1503 loc) · 54.4 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
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
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: SAM-BinaryAlert
Metadata:
AWS::ServerlessRepo::Application:
Name: SAM-BinaryAlert
Description: |-
SAM-BinaryAlert wraps BinaryAlert for deployment with SAR or SAM CLI. (BinaryAlert uses cool Terraform)
BinaryAlert is a serverless, real-time framework for detecting malicious files. (http://www.binaryalert.io/)
Author: Keisuke Konishi
SpdxLicenseId: Apache-2.0
ReadmeUrl: docs/README4SAR.md
LicenseUrl: LICENSE
Labels: [Serverless, Anti-malware, s3, Lambda, Apache2, MadeInJapan]
SemanticVersion: 0.2.1-snapshot
HomePageUrl: https://github.com/komikoni/sam-binaryalert#readme
SourceCodeUrl: https://github.com/komikoni/sam-binaryalert.git
Parameters:
# terraform.tfvars mapping
NamePrefix: # name_prefix
Description: (Require) Prefix used in all resource names (required for uniqueness). E.g. "company_team"
Type: String
MinLength: 3
MaxLength: 50
AllowedPattern: ^[a-z][a-z0-9_]+$
S3LogBucket: # s3_log_bucket
Description: (Option) Pre-existing bucket in which to store S3 access logs. If not specified, one will be created.
Type: String
Default: ""
S3LogPrefix: # s3_log_prefix
Description: (Option) Log files will be stored in S3 with this prefix.
Type: String
Default: "s3-access-logs/"
S3LogExpirationDays: # s3_log_expiration_days
Description: (Option) Access logs expire after this many days. Has no effect if using pre-existing bucket for logs.
Type: Number
Default: 90
LambdaLogRetentionDays: # lambda_log_retention_days
Description: (Option) How long to retain Lambda function logs.
Type: Number
Default: 14
TaggedName: # tagged_name
Description: |
(Option) =Advanced Configuration=
Tags make it easier to organize resources, view grouped billing information, etc.
All supported resources (Dyanmo, KMS, Lambda, S3, SQS) are tagged with
Name = [YOUR_VALUE_BELOW]
Type: String
Default: BinaryAlert
MetricAlarmSnsTopicArn: # metric_alarm_sns_topic_arn
Description: |
(Option) =Alarms=
Use an existing SNS topic for metric alarms (instead of creating one automatically).
ex) arn:aws:sns:ap-northeast-1:999999999999:Topic_Name-0123456789
# ConstraintDescription: Malformed input-Parameter MyParameter must match pattern ^arn:(aws[a-zA-Z-]*)?:sns:[a-z]{2}((-gov)|(-iso(b?)))?-[a-z]+-\d{1}:\d{12}:[a-zA-Z0-9-_]{1,256}$
# AllowedPattern: ^arn:(aws[a-zA-Z-]*)?:sns:[a-z]{2}-[a-z]+-\d{1}:\d{12}:[a-zA-Z0-9-_]{1,256}$
Type: String
Default: ""
ExpectedAnalysisFrequencySeconds: # expected_analysis_frequency_minutes Minutes => Seconds
Description: (Option) Alarm if no binaries are analyzed for this amount of time.
Type: Number
Default: 1800 # 30Minutes * 60
DynamoReadCapacity: # dynamo_read_capacity
Description: |
(Option) =DynamoDB=
Provisioned read/write capacity for the Dynamo table which stores match results.
Capacity is (very roughly) maximum number of operations per second. See Dynamo documentation.
Since there will likely be very few matches, these numbers can be quite low.
Type: Number
Default: 10
DynamoWriteCapacity: # dynamo_write_capacity
Description: (Option)
Type: Number
Default: 5
LambdaAnalyzeMemoryMb: # lambda_analyze_memory_mb
Description: (Option) Memory, time, and concurrency limits for the analyzer function. (128MB - 3008MB Step 64MB)
Type: Number
MinValue: 128
MaxValue: 3008
AllowedValues:
[
128,
192,
256,
320,
384,
448,
512,
576,
640,
704,
768,
832,
896,
960,
1024,
1088,
1152,
1216,
1280,
1344,
1408,
1472,
1536,
1600,
1664,
1728,
1792,
1856,
1920,
1984,
2048,
2112,
2176,
2240,
2304,
2368,
2432,
2496,
2560,
2624,
2688,
2752,
2816,
2880,
2944,
3008,
]
Default: 1024
LambdaAnalyzeTimeoutSec: # lambda_analyze_timeout_sec
Description: "(Option) "
Type: Number
Default: 300
LambdaAnalyzeTimeoutSecPlus2Sec: # lambda_analyze_timeout_sec +2 Sec
Description: "(Option) "
Type: Number
Default: 302
LambdaAnalyzeConcurrencyLimit: # lambda_analyze_concurrency_limit
Description: "(Option) "
Type: Number
Default: 100
ExternalS3BucketResources: # external_s3_bucket_resources
Description: |
(Option) If using BinaryAlert to scan existing S3 buckets, add the S3 and KMS resource ARNs here (separater is "," No spaces before or after the comma)
ex) arn:aws:s3:::bucket-name1/*,arn:aws:s3:::bucket-name2/*
# CommaDelimitedList is not used because the merge of the array will cause a syntax error in the policy document and validation cannot be performed.
Type: String
Default: ""
ExternalKmsKeyResources: # external_kms_key_resources
Description: |
(Option) If using BinaryAlert to scan existing S3 buckets, add the S3 and KMS resource ARNs here (separater is "," No spaces before or after the comma)
ex) arn:aws:kms:ap-northeast-1:999999999999:key/xxxxx,arn:aws:kms:ap-northeast-1:111122223333:alias/ExampleAlias
# CommaDelimitedList is not used because the merge of the array will cause a syntax error in the policy document and validation cannot be performed.
Type: String
Default: ""
EnableNegativeMatchAlerts: # enable_negative_match_alerts
Description: (Option) =SNS= Create a separate SNS topic which reports files that do NOT match any YARA rules. (true or false)
Type: String
AllowedValues:
- "true"
- "false"
Default: "false"
AnalyzeQueueBatchSize: # analyze_queue_batch_size
Description: (Option) =SQS= Maximum number of messages that will be received by each invocation of the respective function.
Type: Number
Default: 10
AnalyzeQueueRetentionSecs: # analyze_queue_retention_secs
Description: (Option) Messages in the queue will be retained and retried for the specified duration until expiring.
Type: Number
Default: 86400
AnalyzeQueueRetentionSecs75Percent: # analyze_queue_retention_secs * 0.75
Description: (Option) AnalyzeQueueRetentionSecs * 0.75
Type: Number
Default: 64800
EnableCarbonBlackDownloader: # enable_carbon_black_downloader
Type: String
AllowedValues:
- "true"
- "false"
Default: "false"
Description: Optional CarbonBlack Downloader
CarbonBlackUrl: # carbon_black_url
Description: URL of the CarbonBlack server.
Type: String
Default: ""
CarbonBlackTimeout: # carbon_black_timeout
Description: |
Timeout to use for Carbon Black API client.
The client default is 60, so set to something lower if desired.
Type: Number
Default: 60
EncryptedCarbonBlackApiToken: # encrypted_carbon_black_api_token
Description: The encrypted CarbonBlack API token will automatically be generated and saved here.
Type: String
Default: ""
LambdaDownloadMemoryMb: # lambda_download_memory_mb
Description: Memory, time, and concurrency limits for the downloader function.
Type: Number
MinValue: 128
MaxValue: 3008
AllowedValues:
[
128,
192,
256,
320,
384,
448,
512,
576,
640,
704,
768,
832,
896,
960,
1024,
1088,
1152,
1216,
1280,
1344,
1408,
1472,
1536,
1600,
1664,
1728,
1792,
1856,
1920,
1984,
2048,
2112,
2176,
2240,
2304,
2368,
2432,
2496,
2560,
2624,
2688,
2752,
2816,
2880,
2944,
3008,
]
Default: 256
LambdaDownloadTimeoutSec: # lambda_download_timeout_sec
Description: ""
Type: Number
Default: 300
LambdaDownloadConcurrencyLimit: # lambda_download_concurrency_limit
Description: ""
Type: Number
Default: 100
DownloadQueueBatchSize: # download_queue_batch_size
Description: =SQS=
Type: Number
Default: 1
DownloadQueueRetentionSecs: # download_queue_retention_secs
Description: ""
Type: Number
Default: 86400
DownloadQueueRetentionSecs75Percent: # download_queue_retention_secs * 0.75
Description: (Option) DownloadQueueRetentionSecs * 0.75
Type: Number
Default: 64800
DownloadQueueMaxReceives: # download_queue_max_receives
Description: |
If an SQS message is not deleted (successfully processed) after the max number of receive
attempts, the message is delivered to the SQS dead-letter queue.
Retries are common due to race-conditions with binaries landing on the Carbon Black server
Type: Number
Default: 100
##### The following parameters are not supported.
#
# ObjectsPerRetroMessage: # objects_per_retro_message
# Description: During a retroactive scan, number of S3 objects to pack into a single SQS message.
# Type: Number
# Default: 4
# ForceDestroy: # force_destroy
# Description: |
# =S3=
# WARNING: If force destroy is enabled, all objects in the S3 bucket(s) will be deleted during
# Type: String
# AllowedValues:
# - "true"
# - "false"
# Default: "true"
Conditions:
EmptyS3LogBucketCondition: !Equals [!Ref S3LogBucket, ""]
EmptyMetricAlarmSnsTopicArnCondition:
!Equals [!Ref MetricAlarmSnsTopicArn, ""]
EnableNegativeMatchAlertsCondition:
!Equals [!Ref EnableNegativeMatchAlerts, "true"]
EmptyExternalS3BucketResourcesCondition:
!Equals [!Ref ExternalS3BucketResources, ""]
EmptyExternalKmsKeyResourcesCondition:
!Equals [!Ref ExternalKmsKeyResources, ""]
EnableCarbonBlackDownloaderCondition:
!Equals [!Ref EnableCarbonBlackDownloader, "true"]
Resources:
S3BucketBinaryalertBinaries: # s3.tf resource aws_s3_bucket binaryalert_binaries
Type: AWS::S3::Bucket
DependsOn:
- SQSQueuePolicyAnalyzer # The queue policy must be created before we can configure the S3 notification.
Properties:
BucketName: !Join
- ""
- - !Join [".", !Split ["_", !Ref NamePrefix]] # replace "_" to "."
- .binaryalert-binaries.
- !Ref AWS::Region
Tags:
- Key: Name
Value: !Ref TaggedName
AccessControl: Private
LoggingConfiguration:
DestinationBucketName: !If
- EmptyS3LogBucketCondition
- !Ref S3BucketBinaryalertLog
- !Ref S3LogBucket
LogFilePrefix: !Ref S3LogPrefix
LifecycleConfiguration:
Rules:
- Id: delete_old_versions
Status: Enabled
NoncurrentVersionExpirationInDays: 1
# https://github.com/aws-cloudformation/aws-cloudformation-coverage-roadmap/issues/132
# ExpiredObjectDeleteMarker: true
- Id: delete_old_inventory
Status: Enabled
ExpirationInDays: 7
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: aws:kms
KMSMasterKeyID: !GetAtt KMSKeySseS3.Arn
InventoryConfigurations:
- Destination:
# BucketArn: !Sub arn:aws:s3:::${NamePrefix}.binaryalert-binaries.${AWS::Region} # self reference
BucketArn: !Join
- ""
- - "arn:aws:s3:::"
- !Join [".", !Split ["_", !Ref NamePrefix]] # replace "_" to "."
- .binaryalert-binaries.
- !Ref AWS::Region
Format: CSV
Prefix: inventory
Enabled: true
Id: EntireBucketDaily
IncludedObjectVersions: Current
ScheduleFrequency: Daily
NotificationConfiguration:
QueueConfigurations:
- Event: s3:ObjectCreated:*
Queue: !GetAtt SQSQueueAnalyzer.Arn
VersioningConfiguration:
Status: Enabled
S3BucketPolicyBinaryalertBinaries: # s3.tf resource aws_s3_bucket_policy allow_inventory
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref S3BucketBinaryalertBinaries
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: AllowSelfInventory
Effect: Allow
Principal:
Service: s3.amazonaws.com
Action: s3:PutObject
Resource: !Sub ${S3BucketBinaryalertBinaries.Arn}/inventory/*
Condition:
StringEquals:
s3:x-amz-acl: bucket-owner-full-control
aws:SourceAccount: !Ref AWS::AccountId
ArnLike:
aws:SourceArn: !GetAtt S3BucketBinaryalertBinaries.Arn
- Sid: ForceSSLOnlyAccess
Effect: Deny
Principal:
AWS: "*"
Action: s3:*
Resource:
- !GetAtt S3BucketBinaryalertBinaries.Arn
- !Sub ${S3BucketBinaryalertBinaries.Arn}/*
Condition:
Bool:
aws:SecureTransport: false
S3BucketBinaryalertLog: # s3.tf resource aws_s3_bucket binaryalert_log_bucket
Type: AWS::S3::Bucket
Condition: EmptyS3LogBucketCondition
Properties:
# BucketName: !Sub ${S3BucketBinaryalertBinaries}.access-logs
BucketName: !Join
- ""
- - !Join [".", !Split ["_", !Ref NamePrefix]] # replace "_" to "."
- .binaryalert-binaries.
- !Ref AWS::Region
- .access-logs
Tags:
- Key: Name
Value: !Ref TaggedName
AccessControl: LogDeliveryWrite
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
LifecycleConfiguration:
Rules:
- Id: log_expiration
Status: Enabled
Transitions:
- TransitionInDays: 30
StorageClass: STANDARD_IA
ExpirationInDays: !Ref S3LogExpirationDays
NoncurrentVersionExpirationInDays: 1
LoggingConfiguration:
LogFilePrefix: self/
VersioningConfiguration:
Status: Enabled
S3BucketPolicyBinaryalertLog: # s3.tf resource aws_s3_bucket_policy force_ssl_only_access
Type: AWS::S3::BucketPolicy
Condition: EmptyS3LogBucketCondition
Properties:
Bucket: !Ref S3BucketBinaryalertLog
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: ForceSSLOnlyAccess
Effect: Deny
Principal:
AWS: "*"
Action: s3:*
Resource:
- !GetAtt S3BucketBinaryalertLog.Arn
- !Sub ${S3BucketBinaryalertLog.Arn}/*
Condition:
Bool:
aws:SecureTransport: false
SQSQueueAnalyzer: # sqs.tf resource aws_sqs_queue analyzer_queue
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub ${NamePrefix}_binaryalert_analyzer_queue
Tags:
- Key: Name
Value: !Ref TaggedName
KmsMasterKeyId: !GetAtt KMSKeySseSqs.Arn
MessageRetentionPeriod: !Ref AnalyzeQueueRetentionSecs
VisibilityTimeout: !Ref LambdaAnalyzeTimeoutSecPlus2Sec
SQSQueuePolicyAnalyzer: # sqs.tf resource aws_sqs_queue_policy analyzer_queue_policy
Type: AWS::SQS::QueuePolicy
Properties:
Queues:
- !Ref SQSQueueAnalyzer
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: AllowBinaryAlertBucketToNotifySQS
Effect: Allow
Principal:
AWS: "*"
Action:
- sqs:SendMessage
Resource: !GetAtt SQSQueueAnalyzer.Arn
Condition:
ArnEquals:
# aws:SourceArn: !Sub arn:aws:s3:::${S3BucketBinaryalertBinaries} # circular reference
aws:SourceArn: !Join
- ""
- - "arn:aws:s3:::"
- !Join [".", !Split ["_", !Ref NamePrefix]] # replace "_" to "."
- .binaryalert-binaries.
- !Ref AWS::Region
LambdaFunctionAnalyzer: # lambda.tf module binaryalert_analyzer
Type: AWS::Serverless::Function
Metadata:
BuildMethod: makefile
# DependOn: IAMPolicy # Not Work https://github.com/awslabs/serverless-application-model/issues/68
Properties:
Description: Analyze a binary with a set of YARA rules
FunctionName: !Sub ${NamePrefix}_binaryalert_analyzer
Tags:
Name: !Ref TaggedName
CodeUri: binaryalert/
Handler: lambda_functions.analyzer.main.analyze_lambda_handler
Runtime: python3.7
MemorySize: !Ref LambdaAnalyzeMemoryMb
Timeout: !Ref LambdaAnalyzeTimeoutSec
ReservedConcurrentExecutions: !Ref LambdaAnalyzeConcurrencyLimit
# Role: !GetAtt IAMRole.Arn
Policies:
- CloudWatchPutMetricPolicy: {}
- SQSPollerPolicy:
QueueName: !GetAtt SQSQueueAnalyzer.QueueName
- DynamoDBCrudPolicy:
TableName: DynamoDBTableYaraMatches
- Statement:
- Sid: QueryAndUpdateDynamo
Effect: Allow
Action:
- dynamodb:UpdateItem
- dynamodb:Query
- dynamodb:PutItem
Resource: !GetAtt DynamoDBTableYaraMatches.Arn
- Sid: DecryptSSE
Effect: Allow
Action:
- kms:Decrypt
- kms:Describe*
Resource: !If
- EmptyExternalKmsKeyResourcesCondition
- - !GetAtt KMSKeySseSqs.Arn
- !GetAtt KMSKeySseS3.Arn
- !Split
- ","
- !Join
- ","
- - !GetAtt KMSKeySseSqs.Arn
- !GetAtt KMSKeySseS3.Arn
- !Ref ExternalKmsKeyResources
- Sid: GetFromS3Bucket
Effect: Allow
Action:
- s3:GetObject*
- s3:HeadObject
Resource: !If
- EmptyExternalS3BucketResourcesCondition
- !Sub ${S3BucketBinaryalertBinaries.Arn}/*
- !Split
- ","
- !Join
- ","
- - !Sub ${S3BucketBinaryalertBinaries.Arn}/*
- !Ref ExternalS3BucketResources
- Sid: PublishAlertsToSNS
Effect: Allow
Action: sns:Publish
Resource:
- !Ref SNSTopicYaraMatchAlerts
- !If
- EnableNegativeMatchAlertsCondition
- !Ref SNSTopicNoYaraMatchAlerts
- !Ref AWS::NoValue
AutoPublishAlias: Production
Events:
AppEvent:
Type: SQS
Properties:
BatchSize: !Ref AnalyzeQueueBatchSize
Queue: !GetAtt SQSQueueAnalyzer.Arn
Enabled: true
Environment:
Variables:
YARA_ALERTS_SNS_TOPIC_ARN: !Ref SNSTopicYaraMatchAlerts
YARA_MATCHES_DYNAMO_TABLE_NAME: !Ref DynamoDBTableYaraMatches
NO_MATCHES_SNS_TOPIC_ARN: !If
- EnableNegativeMatchAlertsCondition
- !Ref SNSTopicNoYaraMatchAlerts
- ""
CloudWatchLogsLogGroupLambdaAnalyzer: # main.tf resource aws_cloudwatch_log_group lambda_log_group
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub /aws/lambda/${LambdaFunctionAnalyzer}
RetentionInDays: !Ref LambdaLogRetentionDays
CloudWatchAlarmLambdaAnalyzerErrors: # main.tf resource aws_cloudwatch_metric_alarm lambda_errors
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub ${LambdaFunctionAnalyzer}_errors
AlarmDescription: !Sub ${LambdaFunctionAnalyzer} has a high error rate. Check the CloudWatch logs.
AlarmActions:
- !If
- EmptyMetricAlarmSnsTopicArnCondition
- !Ref SNSTopicMetricAlarms
- !Ref MetricAlarmSnsTopicArn
MetricName: Errors
Namespace: AWS/Lambda
Statistic: Sum
Dimensions:
- Name: FunctionName
Value: !Ref LambdaFunctionAnalyzer
- Name: Resource
Value: !Sub ${LambdaFunctionAnalyzer}:Production
Period: 300
EvaluationPeriods: 1
Threshold: 10
ComparisonOperator: GreaterThanOrEqualToThreshold
TreatMissingData: missing
DynamoDBTableYaraMatches: # dynamo.tf resource aws_dynamodb_table binaryalert_yara_matches
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub ${NamePrefix}_binaryalert_matches
KeySchema:
- AttributeName: SHA256
KeyType: HASH
- AttributeName: AnalyzerVersion
KeyType: RANGE
ProvisionedThroughput:
ReadCapacityUnits: !Ref DynamoReadCapacity
WriteCapacityUnits: !Ref DynamoWriteCapacity
AttributeDefinitions:
- AttributeName: AnalyzerVersion
AttributeType: N
- AttributeName: SHA256
AttributeType: S
SSESpecification:
SSEEnabled: true
SSEType: KMS
Tags:
- Key: Name
Value: !Ref TaggedName
SNSTopicYaraMatchAlerts: # sns.tf resource aws_sns_topic yara_match_alerts
Type: AWS::SNS::Topic
Properties:
DisplayName: YARA match alerts will be published to this SNS topic.
TopicName: !Sub ${NamePrefix}_binaryalert_yara_match_alerts
SNSTopicPolicyYaraMatchAlerts:
Type: AWS::SNS::TopicPolicy
Properties:
Topics:
- !Ref SNSTopicYaraMatchAlerts
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: __default_statement_ID
Effect: Allow
Principal:
AWS: "*"
Action:
- SNS:GetTopicAttributes
- SNS:SetTopicAttributes
- SNS:AddPermission
- SNS:RemovePermission
- SNS:DeleteTopic
- SNS:Subscribe
- SNS:ListSubscriptionsByTopic
- SNS:Publish
- SNS:Receive
Resource: !Ref SNSTopicYaraMatchAlerts
Condition:
StringEquals:
AWS:SourceOwner: !Sub ${AWS::AccountId}
SNSTopicNoYaraMatchAlerts: # sns.tf resource aws_sns_topic no_yara_match
Type: AWS::SNS::Topic
Condition: EnableNegativeMatchAlertsCondition
Properties:
DisplayName: If a file does NOT match any YARA rules, notify this SNS topic.
TopicName: !Sub ${NamePrefix}_binaryalert_no_yara_match
SNSTopicPolicyNoYaraMatchAlerts:
Type: AWS::SNS::TopicPolicy
Condition: EnableNegativeMatchAlertsCondition
Properties:
Topics:
- !Ref SNSTopicNoYaraMatchAlerts
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: __default_statement_ID
Effect: Allow
Principal:
AWS: "*"
Action:
- SNS:GetTopicAttributes
- SNS:SetTopicAttributes
- SNS:AddPermission
- SNS:RemovePermission
- SNS:DeleteTopic
- SNS:Subscribe
- SNS:ListSubscriptionsByTopic
- SNS:Publish
- SNS:Receive
Resource: !Ref SNSTopicNoYaraMatchAlerts
Condition:
StringEquals:
AWS:SourceOwner: !Sub ${AWS::AccountId}
SNSTopicMetricAlarms: # sns.tf resource aws_sns_topic metric_alarms
Type: AWS::SNS::Topic
Condition: EmptyMetricAlarmSnsTopicArnCondition
Properties:
DisplayName: CloudWatch metric alarms notify this SNS topic (created only if an existing one is not specified)
TopicName: !Sub ${NamePrefix}_binaryalert_metric_alarms
SNSTopicPolicyMetricAlarms:
Type: AWS::SNS::TopicPolicy
Condition: EmptyMetricAlarmSnsTopicArnCondition
Properties:
Topics:
- !Ref SNSTopicMetricAlarms
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: __default_statement_ID
Effect: Allow
Principal:
AWS: "*"
Action:
- SNS:GetTopicAttributes
- SNS:SetTopicAttributes
- SNS:AddPermission
- SNS:RemovePermission
- SNS:DeleteTopic
- SNS:Subscribe
- SNS:ListSubscriptionsByTopic
- SNS:Publish
- SNS:Receive
Resource: !Ref SNSTopicMetricAlarms
Condition:
StringEquals:
AWS:SourceOwner: !Sub ${AWS::AccountId}
# IAMRole: # main.tf resource aws_iam_role role
# Type: AWS::IAM::Role
# Properties:
# Path: /
# # RoleName: !Sub ${NamePrefix}_binaryalert_analyzer_role # Only works with CAPABILITY_IAM
# AssumeRolePolicyDocument:
# Version: 2012-10-17
# Statement:
# - Sid: AllowLambdaToAssumeRole
# Effect: Allow
# Principal:
# Service: lambda.amazonaws.com
# Action: sts:AssumeRole
# ManagedPolicyArns:
# - arn:aws:iam::aws:policy/service-role/AWSLambdaSQSQueueExecutionRole # add
# - !Ref IAMManagedPolicy
# IAMManagedPolicy: # lambda_iam.tf resource aws_iam_policy base_policy
# Type: AWS::IAM::ManagedPolicy
# Properties:
# # ManagedPolicyName: !Sub ${NamePrefix}_binaryalert_base_policy # Only works with CAPABILITY_IAM
# Path: /
# PolicyDocument:
# Version: 2012-10-17
# Statement:
# - Sid: EnableLogsAndMetrics
# Effect: Allow
# Action:
# - logs:PutLogEvents
# - logs:CreateLogStream
# - logs:CreateLogGroup
# - cloudwatch:PutMetricData
# Resource: "*"
# IAMPolicy: # lambda_iam.tf resource aws_iam_role_policy binaryalert_analyzer_policy
# Type: AWS::IAM::Policy
# Properties:
# PolicyName: !Sub ${LambdaFunctionAnalyzer}_policy
# Roles:
# - !Ref IAMRole
# PolicyDocument:
# Version: 2012-10-17
# Statement:
# - Sid: QueryAndUpdateDynamo
# Effect: Allow
# Action:
# - dynamodb:UpdateItem
# - dynamodb:Query
# - dynamodb:PutItem
# Resource: !GetAtt DynamoDBTableYaraMatches.Arn
# - Sid: DecryptSSE
# Effect: Allow
# Action:
# - kms:Decrypt
# - kms:Describe*
# Resource: !If
# - EmptyExternalKmsKeyResourcesCondition
# - - !GetAtt KMSKeySseSqs.Arn
# - !GetAtt KMSKeySseS3.Arn
# - !Split
# - ","
# - !Join
# - ","
# - - !GetAtt KMSKeySseSqs.Arn
# - !GetAtt KMSKeySseS3.Arn
# - !Ref ExternalKmsKeyResources
# - Sid: GetFromS3Bucket
# Effect: Allow
# Action:
# - s3:GetObject*
# - s3:HeadObject
# Resource: !If
# - EmptyExternalS3BucketResourcesCondition
# - !Sub ${S3BucketBinaryalertBinaries.Arn}/*
# - !Split
# - ","
# - !Join
# - ","
# - - !Sub ${S3BucketBinaryalertBinaries.Arn}/*
# - !Ref ExternalS3BucketResources
# - Sid: PublishAlertsToSNS
# Effect: Allow
# Action: sns:Publish
# Resource:
# - !Ref SNSTopicYaraMatchAlerts
# - !If
# - EnableNegativeMatchAlertsCondition
# - !Ref SNSTopicNoYaraMatchAlerts
# - !Ref AWS::NoValue
# - Sid: ProcessSQSMessages
# Effect: Allow
# Action:
# - sqs:ReceiveMessage
# - sqs:GetQueueAttributes
# - sqs:DeleteMessage
# - sqs:ChangeMessageVisibility
# Resource: !GetAtt SQSQueueAnalyzer.Arn
KMSKeySseS3: # kms.tf resource aws_kms_key sse_s3
Type: AWS::KMS::Key
Properties:
Enabled: true
Description: BinaryAlert Server-Side Encryption - S3
EnableKeyRotation: true
Tags:
- Key: Name
Value: !Ref TaggedName
KeyPolicy:
Version: 2012-10-17
Statement:
- Sid: Enable IAM User Permissions
Effect: Allow
Principal:
AWS: !Sub arn:aws:iam::${AWS::AccountId}:root
Action: kms:*
Resource: "*"
- Sid: AllowS3ToUseKey
Effect: Allow
Principal:
Service: s3.amazonaws.com
Action:
- kms:Decrypt
- kms:GenerateDataKey*
Resource: "*"
KMSAliasSseS3: # kms.tf resource aws_kms_alias sse_s3_alias
Type: AWS::KMS::Alias
Properties:
AliasName: !Sub arn:aws:kms:${AWS::Region}:${AWS::AccountId}:alias/${NamePrefix}_binaryalert_sse_s3
TargetKeyId: !Ref KMSKeySseS3
KMSKeySseSqs: # kms.tf resource aws_kms_key sse_sqs
Type: AWS::KMS::Key
Properties:
Enabled: true
Description: BinaryAlert Server-Side Encryption - SQS
EnableKeyRotation: true
Tags:
- Key: Name
Value: !Ref TaggedName
KeyPolicy:
Version: 2012-10-17
Statement:
- Sid: Enable IAM User Permissions
Effect: Allow
Principal:
AWS: !Sub arn:aws:iam::${AWS::AccountId}:root
Action: kms:*
Resource: "*"
- Sid: AllowS3ToUseKey
Effect: Allow
Principal:
Service: s3.amazonaws.com
Action:
- kms:Decrypt
- kms:GenerateDataKey*
Resource: "*"
KMSAliasSseSqs: # kms.tf resource aws_kms_alias sse_sqs_alias
Type: AWS::KMS::Alias
Properties:
AliasName: !Sub arn:aws:kms:${AWS::Region}:${AWS::AccountId}:alias/${NamePrefix}_binaryalert_sse_sqs
TargetKeyId: !Ref KMSKeySseSqs
CloudWatchAlarmNoAnalyzedBinaries: # cloudwatch_metric_alarm.tf resource aws_cloudwatch_metric_alarm analyzed_binaries
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub ${LambdaFunctionAnalyzer}_no_analyzed_binaries
AlarmDescription: !Sub |
${LambdaFunctionAnalyzer} is not analyzing any binaries!
- If any BinaryAlert Lambda function was recently deployed, roll it back via the AWS console.
- Binaries may not be arriving in the S3 bucket.
Namespace: BinaryAlert
MetricName: AnalyzedBinaries
Statistic: Sum
ComparisonOperator: LessThanOrEqualToThreshold
Threshold: 0
Period: !Ref ExpectedAnalysisFrequencySeconds
EvaluationPeriods: 1
AlarmActions:
- !If
- EmptyMetricAlarmSnsTopicArnCondition
- !Ref SNSTopicMetricAlarms
- !Ref MetricAlarmSnsTopicArn
InsufficientDataActions:
- !If
- EmptyMetricAlarmSnsTopicArnCondition
- !Ref SNSTopicMetricAlarms
- !Ref MetricAlarmSnsTopicArn
CloudWatchAlarmAnalyzerSqsAge: # cloudwatch_metric_alarm.tf resource aws_cloudwatch_metric_alarm analyzer_sqs_age
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub ${SQSQueueAnalyzer.QueueName}_old_age
AlarmDescription: !Sub |
The queue ${SQSQueueAnalyzer.QueueName} is not being processed quickly enough:
messages are reaching 75% of the queue retention and may be expired soon.
- Consider increasing the lambda_analyze_concurrency_limit to process more events
- Consider raising the retention period for this queue
Namespace: AWS/SQS
MetricName: ApproximateAgeOfOldestMessage
Statistic: Minimum
Dimensions:
- Name: QueueName
Value: !GetAtt SQSQueueAnalyzer.QueueName
ComparisonOperator: GreaterThanThreshold
Threshold: !Ref AnalyzeQueueRetentionSecs75Percent
Period: 60
EvaluationPeriods: 10
AlarmActions:
- !If
- EmptyMetricAlarmSnsTopicArnCondition
- !Ref SNSTopicMetricAlarms
- !Ref MetricAlarmSnsTopicArn
InsufficientDataActions:
- !If
- EmptyMetricAlarmSnsTopicArnCondition
- !Ref SNSTopicMetricAlarms
- !Ref MetricAlarmSnsTopicArn
CloudWatchAlarmYaraRules: # cloudwatch_metric_alarm.tf resource aws_cloudwatch_metric_alarm yara_rules
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: !Sub ${LambdaFunctionAnalyzer}_too_few_yara_rules
AlarmDescription: |
The number of YARA rules in BinaryAlert is surprisingly low.
Check if a recent deploy accidentally removed most YARA rules.
Namespace: BinaryAlert
MetricName: YaraRules
Statistic: Maximum
ComparisonOperator: LessThanThreshold
Threshold: 5
Period: 300
EvaluationPeriods: 1
AlarmActions:
- !If
- EmptyMetricAlarmSnsTopicArnCondition
- !Ref SNSTopicMetricAlarms
- !Ref MetricAlarmSnsTopicArn
CloudWatchAlarmDynamoThrottles: # cloudwatch_metric_alarm.tf resource aws_cloudwatch_metric_alarm dynamo_throttles
Type: AWS::CloudWatch::Alarm
Properties: