-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.yaml
executable file
·9892 lines (8480 loc) · 391 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
Transform: AWS::Serverless-2016-10-31
Metadata:
"AWS::CloudFormation::Interface":
ParameterGroups:
- Label:
default: "General S3 Parameters"
Parameters:
- BucketName
- Label:
default: "SageMaker Model ARN"
Parameters:
- TechniqueModelARN
- ClusterModelARN
- FlowModelARN
- Label:
default: UI admin credentials
Parameters:
- SuperuserEmail
- SuperuserUsername
- SuperuserPassword
- Label:
default: Container images
Parameters:
- NginxContainerImage
- WebContainerImage
- VRLLambdaImage
- Label:
default: "Load Balancer Configuration"
Parameters:
- LoadBalancerName
- Label:
default: "SageMaker Model Parameters"
Parameters:
- TechniqueModelName
- ClusterModelName
- FlowModelName
- Label:
default: "Input processing Parameters"
Parameters:
- TechniqueLookupObject
- ChunkSize
- FlowInputMaxClusters
- Label:
default: "Technique detector Batch Job Parameters"
Parameters:
- EnrichTechBatchInstanceType
- EnrichTechBatchTimeout
- Label:
default: "Temporal clustering Batch Job Parameters"
Parameters:
- ClusterBatchInstanceType
- ClusterBatchTimeout
- Label:
default: "Flow detector Batch Job Parameters"
Parameters:
- FlowBatchInstanceType
- FlowBatchTimeout
- Label:
default: "UI lambda function Parameters"
Parameters:
- ClusterOrFlowMapToCampaign
- EventThreshold
- TacticThreshold
- Label:
default: "Lambda Function Parameters"
Parameters:
- SplunkInputFunctionName
- VRLLambdaFunctionName
- EnrichTechFunctionName
- ProcessTechFunctionName
- CreateClusterFunctionName
- ProcessClusterFunctionName
- CreateFlowFunctionName
- ProcessFlowFunctionName
- UpdateLookupFunctionName
- CreateCampaignFunctionName
- SaveFeedbackFunctionName
- Label:
default: "ECS Configuration"
Parameters:
- ECSClusterName
- ServiceAndTaskDefinitionName
- Cpu
- Memory
- LatestECSOptimizedAMI
- Label:
default: "Auto Scaling Configuration"
Parameters:
- ClusterAutoScalingMinSize
- ClusterAutoScalingMaxSize
- Label:
default: "VPC Configuration"
Parameters:
- VPCNamePrefix
- VpcCidr
- Subnet1Cidr
- Subnet2Cidr
Parameters:
BucketName:
Type: String
Description: Name of the S3 bucket to create.
MinLength: 1
TechniqueModelName:
Type: String
Description: Name of Sagemaker model for technique classification
Default: technique-model
MinLength: 1
TechniqueModelARN:
Type: String
Description: Model package ARN for the technique model subscribed from marketplace
MinLength: 1
AllowedPattern: ^arn:aws(-[a-z]+)*:[a-zA-Z0-9\-]+:[a-z0-9\-]*:[0-9]{12}:(.+)$
ConstraintDescription: Enter a valid AWS ARN for technique model
ClusterModelName:
Type: String
Description: Name of Sagemaker model for cluster detection
Default: cluster-model
MinLength: 1
ClusterModelARN:
Type: String
Description: Model package ARN for the cluster model subscribed from marketplace
MinLength: 1
AllowedPattern: ^arn:aws(-[a-z]+)*:[a-zA-Z0-9\-]+:[a-z0-9\-]*:[0-9]{12}:(.+)$
ConstraintDescription: Enter a valid AWS ARN for technique model
FlowModelName:
Type: String
Description: Name of Sagemaker model for flow detection
Default: flow-model
MinLength: 1
FlowModelARN:
Type: String
Description: Model package ARN for the flow model subscribed from marketplace
MinLength: 1
AllowedPattern: ^arn:aws(-[a-z]+)*:[a-zA-Z0-9\-]+:[a-z0-9\-]*:[0-9]{12}:(.+)$
ConstraintDescription: Enter a valid AWS ARN for technique model
VRLLambdaImage:
Description: VRL Lambda ECR container image URI
Type: String
MinLength: 8
ConstraintDescription: Must be minimum length of 8
TechniqueLookupObject:
Type: String
Description: Path to S3 object where you want to save lookup table for previously classified techniques for alerts. The object file must have an extension of '.csv'
Default: "scratch/lambda/data.csv"
MinLength: 5
ChunkSize:
Type: Number
Description: Size of single chunk of input to be processed at a time for an input file
Default: 20000
EnrichTechBatchInstanceType:
Type: String
Default: ml.p2.xlarge
Description: EC2 instance type for the enrich technology batch transform job.
AllowedValues:
- ml.p2.xlarge
- ml.p2.8xlarge
- ml.p2.16xlarge
- ml.p3.2xlarge
- ml.p3.8xlarge
- ml.p3.16xlarge
EnrichTechBatchTimeout:
Type: Number
Default: 3600
Description: Timeout in seconds for the enrich technology batch transform job. Minimum allowed value '1'. Maximum allowed value '3600'
MinValue: 1
MaxValue: 3600
ClusterBatchInstanceType:
Type: String
Default: ml.p3.2xlarge
Description: EC2 instance type for the cluster batch transform job.
AllowedValues:
- ml.p3.2xlarge
- ml.p3.8xlarge
- ml.p3.16xlarge
ClusterBatchTimeout:
Type: Number
Default: 3600
Description: Timeout in seconds for the cluster batch transform job. Minimum allowed value '1'. Maximum allowed value '3600'
MinValue: 1
MaxValue: 3600
FlowBatchInstanceType:
Type: String
Default: ml.c5.4xlarge
Description: EC2 instance type for the flow batch transform job.
AllowedValues:
- ml.m5.xlarge
- ml.m5.2xlarge
- ml.m5.4xlarge
- ml.m5.12xlarge
- ml.m5.24xlarge
- ml.m4.xlarge
- ml.m4.2xlarge
- ml.m4.4xlarge
- ml.m4.10xlarge
- ml.c5.xlarge
- ml.c5.2xlarge
- ml.c5.4xlarge
- ml.c5.9xlarge
- ml.c5.18xlarge
- ml.c4.xlarge
- ml.c4.2xlarge
- ml.c4.4xlarge
- ml.c4.8xlarge
- ml.m4.16xlarge
FlowBatchTimeout:
Type: Number
Default: 3600
Description: Timeout in seconds for the flow batch transform job. Minimum allowed value '1'. Maximum allowed value '3600'
MinValue: 1
MaxValue: 3600
FlowInputMaxClusters:
Type: Number
Description: Number of clusters as input to Flow detection model to be processed at a time for an input file
Default: 5000
SplunkInputFunctionName:
Type: String
Default: splunk_input
Description: Function name for process splunk input.
MinLength: 5
VRLLambdaFunctionName:
Type: String
Default: vrl_lambda
Description: Function name for VRL transform.
MinLength: 5
EnrichTechFunctionName:
Type: String
Default: enrich_with_technique
Description: Function name for enriching with technique.
MinLength: 5
ProcessTechFunctionName:
Type: String
Default: process_enriched_with_technique
Description: Function name for processing enriched data with technique.
MinLength: 5
CreateClusterFunctionName:
Type: String
Default: create_cluster
Description: Function name for creating cluster.
MinLength: 5
ProcessClusterFunctionName:
Type: String
Default: process_cluster
Description: Function name for processing cluster.
MinLength: 5
CreateFlowFunctionName:
Type: String
Default: create_flow
Description: Function name for creating flow.
MinLength: 5
ProcessFlowFunctionName:
Type: String
Default: process_flow
Description: Function name for processing flow.
MinLength: 5
UpdateLookupFunctionName:
Type: String
Default: update_lookup_table
Description: Function name for updating the lookup table.
MinLength: 5
CreateCampaignFunctionName:
Type: String
Default: create_campaign
Description: Function name for creating campaigns on UI.
MinLength: 5
SaveFeedbackFunctionName:
Type: String
Default: save_feedback
Description: Function name for fetching copy/cut action feedback from UI.
MinLength: 5
ClusterOrFlowMapToCampaign:
Type: String
Default: cluster
AllowedValues:
- cluster
- flow
EventThreshold:
Type: Number
Default: 2
Description: Number of events present in the cluster or flow to create campaign on UI. Minimum allowed value '1'.
MinValue: 1
TacticThreshold:
Type: Number
Default: 0
Description: Number of tactics present in an event to be part of the campaign. Minimum allowed value '0'.
MinValue: 0
ECSClusterName:
Type: String
Description: Specifies the ECS Cluster Name with which the resources would be associated
Default: cypienta-cluster
MinLength: 3
ConstraintDescription: Must be minimum length of 3
ECSClusterInstanceType:
Type: String
Description: ECS Cluster instance type for EC2
Default: t3a.large
AllowedValues:
- t2.micro
- t2.small
- t2.medium
- t2.large
- t3.micro
- t3.small
- t3.medium
- t3.large
- t3a.micro
- t3a.small
- t3a.medium
- t3a.large
- m5.large
- m5.xlarge
- m5.2xlarge
- m5.4xlarge
- m5a.large
- m5a.xlarge
- m5a.2xlarge
- m5a.4xlarge
- m6g.medium
- m6g.large
- m6g.xlarge
- m6g.2xlarge
ServiceAndTaskDefinitionName:
Description: Name of the ECS task definition and ECS Service
Type: String
Default: cypienta-ui
MinLength: 3
ConstraintDescription: Must be minimum length of 3
Cpu:
Description: Number of CPU units used by the task. 1 vCPU = 1024
Type: String
Default: 1024
AllowedValues:
- 256
- 512
- 1024
- 2048
- 4096
- 8192
- 16384
Memory:
Description: Amount of memory (in MiB) used by the task. 1 GB = 1024
Type: String
Default: 4096
AllowedPattern: ^[0-9]+$
ConstraintDescription: Must be an integer value
SuperuserEmail:
Description: Email of superuser
Type: String
AllowedPattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$"
ConstraintDescription: Must be a valid email address
SuperuserUsername:
Description: Superuser username. Minimum length of 3.
Type: String
MinLength: 3
ConstraintDescription: Must be minimum length of 3
SuperuserPassword:
Description: Superuser password. Minimum length of 8
Type: String
MinLength: 8
ConstraintDescription: Must be minimum length of 8
NginxContainerImage:
Description: Nginx container image with tag nginx-market*
Type: String
MinLength: 8
ConstraintDescription: Must be minimum length of 8
WebContainerImage:
Description: Container image for web app with tag market*
Type: String
MinLength: 8
ConstraintDescription: Must be minimum length of 8
VPCNamePrefix:
Description: Prefix for naming VPC and corresponding resources
Type: String
Default: cypienta
MinLength: 3
ConstraintDescription: Must be minimum length of 3
VpcCidr:
Description: The CIDR block for the VPC
Type: String
Default: 10.0.0.0/16
AllowedPattern: ^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$
ConstraintDescription: Must be a valid CIDR block of the form x.x.x.x/x
Subnet1Cidr:
Description: The CIDR block for the first public subnet
Type: String
Default: 10.0.0.0/20
AllowedPattern: ^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$
ConstraintDescription: Must be a valid CIDR block of the form x.x.x.x/x
Subnet2Cidr:
Description: The CIDR block for the second public subnet
Type: String
Default: 10.0.16.0/20
AllowedPattern: ^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$
ConstraintDescription: Must be a valid CIDR block of the form x.x.x.x/x
LoadBalancerName:
Description: Name of Load balancer
Type: String
Default: cypienta-ui
MinLength: 3
ConstraintDescription: Must be minimum length of 3
ClusterAutoScalingMinSize:
Description: The minimum size of the auto scaling group for the ECS cluster
Type: String
Default: 0
AllowedPattern: ^[0-9]+$
ConstraintDescription: Must be an integer value
ClusterAutoScalingMaxSize:
Description: The maximum size of the auto scaling group for the ECS cluster
Type: String
Default: 5
AllowedPattern: ^[0-9]+$
ConstraintDescription: Must be an integer value
LatestECSOptimizedAMI:
Description: AMI ID
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id
Mappings:
RegionMap:
af-south-1:
lambdaLayer: 'arn:aws:lambda:af-south-1:336392948345:layer:AWSSDKPandas-Python311:12'
ap-northeast-1:
lambdaLayer: >-
arn:aws:lambda:ap-northeast-1:336392948345:layer:AWSSDKPandas-Python311:12
ap-northeast-2:
lambdaLayer: >-
arn:aws:lambda:ap-northeast-2:336392948345:layer:AWSSDKPandas-Python311:12
ap-northeast-3:
lambdaLayer: >-
arn:aws:lambda:ap-northeast-3:336392948345:layer:AWSSDKPandas-Python311:12
ap-south-1:
lambdaLayer: 'arn:aws:lambda:ap-south-1:336392948345:layer:AWSSDKPandas-Python311:12'
ap-southeast-1:
lambdaLayer: >-
arn:aws:lambda:ap-southeast-1:336392948345:layer:AWSSDKPandas-Python311:12
ap-southeast-2:
lambdaLayer: >-
arn:aws:lambda:ap-southeast-2:336392948345:layer:AWSSDKPandas-Python311:12
ca-central-1:
lambdaLayer: 'arn:aws:lambda:ca-central-1:336392948345:layer:AWSSDKPandas-Python311:12'
eu-central-1:
lambdaLayer: 'arn:aws:lambda:eu-central-1:336392948345:layer:AWSSDKPandas-Python311:12'
eu-north-1:
lambdaLayer: 'arn:aws:lambda:eu-north-1:336392948345:layer:AWSSDKPandas-Python311:12'
eu-west-1:
lambdaLayer: 'arn:aws:lambda:eu-west-1:336392948345:layer:AWSSDKPandas-Python311:12'
eu-west-2:
lambdaLayer: 'arn:aws:lambda:eu-west-2:336392948345:layer:AWSSDKPandas-Python311:12'
eu-west-3:
lambdaLayer: 'arn:aws:lambda:eu-west-3:336392948345:layer:AWSSDKPandas-Python311:12'
sa-east-1:
lambdaLayer: 'arn:aws:lambda:sa-east-1:336392948345:layer:AWSSDKPandas-Python311:12'
us-east-1:
lambdaLayer: 'arn:aws:lambda:us-east-1:336392948345:layer:AWSSDKPandas-Python311:12'
us-east-2:
lambdaLayer: 'arn:aws:lambda:us-east-2:336392948345:layer:AWSSDKPandas-Python311:12'
us-west-1:
lambdaLayer: 'arn:aws:lambda:us-west-1:336392948345:layer:AWSSDKPandas-Python311:12'
us-west-2:
lambdaLayer: 'arn:aws:lambda:us-west-2:336392948345:layer:AWSSDKPandas-Python311:12'
ap-east-1:
lambdaLayer: 'arn:aws:lambda:ap-east-1:839552336658:layer:AWSSDKPandas-Python311:14'
ap-south-2:
lambdaLayer: 'arn:aws:lambda:ap-south-2:246107603503:layer:AWSSDKPandas-Python311:13'
ap-southeast-3:
lambdaLayer: >-
arn:aws:lambda:ap-southeast-3:258944054355:layer:AWSSDKPandas-Python311:14
ap-southeast-4:
lambdaLayer: >-
arn:aws:lambda:ap-southeast-4:945386623051:layer:AWSSDKPandas-Python311:13
eu-central-2:
lambdaLayer: 'arn:aws:lambda:eu-central-2:956415814219:layer:AWSSDKPandas-Python311:13'
eu-south-1:
lambdaLayer: 'arn:aws:lambda:eu-south-1:774444163449:layer:AWSSDKPandas-Python311:14'
eu-south-2:
lambdaLayer: 'arn:aws:lambda:eu-south-2:982086096842:layer:AWSSDKPandas-Python311:13'
il-central-1:
lambdaLayer: 'arn:aws:lambda:il-central-1:263840725265:layer:AWSSDKPandas-Python311:12'
me-central-1:
lambdaLayer: 'arn:aws:lambda:me-central-1:593833071574:layer:AWSSDKPandas-Python311:12'
me-south-1:
lambdaLayer: 'arn:aws:lambda:me-south-1:938046470361:layer:AWSSDKPandas-Python311:14'
cn-north-1:
lambdaLayer: >-
arn:aws-cn:lambda:cn-north-1:406640652441:layer:AWSSDKPandas-Python311:10
cn-northwest-1:
lambdaLayer: >-
arn:aws-cn:lambda:cn-northwest-1:406640652441:layer:AWSSDKPandas-Python311:10
Resources:
Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Ref BucketName
SagemakerRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: sagemaker.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonSageMakerFullAccess
Policies:
- PolicyName: S3access
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
- s3:DeleteObject
- s3:ListBucket
Resource:
- arn:aws:s3:::*
LambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonSageMakerServiceCatalogProductsLambdaServiceRolePolicy
- arn:aws:iam::aws:policy/AmazonS3FullAccess
TechModel:
Type: AWS::SageMaker::Model
Properties:
Containers:
- ModelPackageName: !Ref TechniqueModelARN
ExecutionRoleArn: !GetAtt SagemakerRole.Arn
ModelName: !Ref TechniqueModelName
EnableNetworkIsolation: true
ClusterModel:
Type: AWS::SageMaker::Model
Properties:
Containers:
- ModelPackageName: !Ref ClusterModelARN
ExecutionRoleArn: !GetAtt SagemakerRole.Arn
ModelName: !Ref ClusterModelName
EnableNetworkIsolation: true
FlowModel:
Type: AWS::SageMaker::Model
Properties:
Containers:
- ModelPackageName: !Ref FlowModelARN
ExecutionRoleArn: !GetAtt SagemakerRole.Arn
ModelName: !Ref FlowModelName
EnableNetworkIsolation: true
splunkInput:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Ref SplunkInputFunctionName
Description: !Sub
- Stack ${AWS::StackName} Function ${ResourceName}
- ResourceName: splunkInput
InlineCode: |
'''
Chunk input from splunk to create input for VRL transform.
Merge back chunks for single input file back to one and send as input to pipeline.
Input: Input from splunk Add-on Amazon S3 Uploader for Splunk (json format)
'''
import os
import sys
import subprocess
import json
import glob
import urllib
import boto3
from itertools import islice
import gc
# Install ijson pip library to handle large json input files
os.makedirs("/tmp/pylib", exist_ok=True)
subprocess.call('pip install ijson==3.3.0 -t /tmp/pylib/ --no-cache-dir'.split(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
sys.path.insert(1, '/tmp/pylib/')
import ijson
CHUNK_SIZE = int(os.getenv("chunk_size"))
missing_variables = []
if CHUNK_SIZE is None:
missing_variables.append("chunk_size")
if missing_variables:
raise ValueError(f"Please enter environment variable(s): {missing_variables}")
S3_CLIENT = boto3.client("s3")
SCRATCH_DIR = "scratch"
BUF_SIZE = 1*1024*1024
TEMP_INPUT_DIR = "/tmp/input/"
os.makedirs(TEMP_INPUT_DIR, exist_ok=True)
def lambda_handler(event, context):
'''
Read input file and split in chunks
'''
global S3_CLIENT
global CHUNK_SIZE
func = "lambda_handler"
input_file_object = urllib.parse.unquote_plus(event["Records"][0]["s3"]["object"]["key"], encoding="utf-8")
clear_temp_dir()
print(f"{func}: Input file object: {input_file_object}")
prefix = "/".join(input_file_object.split("/")[:2])
if prefix == "splunk_input/input":
process_splunk_input(event, context)
else:
merge_transformed_input(event, context)
def merge_transformed_input(event, context):
'''
Read chunk transformed input file and merge it to be input to pipeline
'''
global S3_CLIENT
func = "merge_transformed_input"
bucket = event["Records"][0]["s3"]["bucket"]["name"]
input_file_object = urllib.parse.unquote_plus(event["Records"][0]["s3"]["object"]["key"], encoding="utf-8")
input_file = "/tmp/chunk_input.json"
clear_temp_dir()
try:
print(f"{func}: Download input file: {bucket}/{input_file_object}")
S3_CLIENT.download_file(bucket, input_file_object, input_file)
except Exception as e:
print(f"{func}: Failed to download file from S3: {bucket}/{input_file_object}")
raise e
print(f"{func}: Check if all splits are processed")
input_file_name = input_file_object.split("/")[-2]
input_file_splits_length_json_filename = f"splunk_input/{SCRATCH_DIR}/count/{input_file_name}/split_length.json"
temp_input_file_splits_length_json_filename = f"/tmp/split_length.json"
try:
print(f"{func}: Download length file: {bucket}/{input_file_splits_length_json_filename}")
S3_CLIENT.download_file(bucket, input_file_splits_length_json_filename, temp_input_file_splits_length_json_filename)
except Exception as e:
print(f"{func}: Failed to download file from S3: {bucket}/{input_file_splits_length_json_filename}")
raise e
length_json = json.load(open(temp_input_file_splits_length_json_filename, "r"))
prefix = f"splunk_input/{SCRATCH_DIR}/transformed/{input_file_name}/"
print(f"{func}: Prefix to search: {prefix}")
paginator = S3_CLIENT.get_paginator('list_objects_v2')
page_iterator = paginator.paginate(Bucket=bucket, Prefix=prefix)
completed_chunk_keys = []
print(f"{func}: Iterate through each page")
for page in page_iterator:
if 'Contents' in page:
for obj in page['Contents']:
completed_chunk_keys.append(obj['Key'])
print(f"{func}: Total files in prefix: {len(completed_chunk_keys)}")
if len(completed_chunk_keys) != length_json["count"]:
print(f"{func}: All chunk did not complete processing. Skip merge")
return
print(f"{func}: All chunks completed processing. Merge chunks and upload to S3")
input_to_pipeline_filename = "/tmp/input_pipe.json"
with open(input_to_pipeline_filename, "w") as f_write:
f_write.write("""{"input": [""")
first_line_present = False
for chunk_key in completed_chunk_keys:
completed_chunk_filename = f"{TEMP_INPUT_DIR}chunk.json"
try:
print(f"{func}: Download input file: {bucket}/{chunk_key}")
S3_CLIENT.download_file(bucket, chunk_key, completed_chunk_filename)
except Exception as e:
print(f"{func}: Failed to download file from S3: {bucket}/{chunk_key}")
raise e
print("read and add chunk contents")
with open(completed_chunk_filename, "r") as f_read:
for line in f_read:
if first_line_present:
f_write.write(",\n" + line.strip("\n"))
else:
f_write.write("\n" + line.strip("\n"))
first_line_present = True
f_write.write("]}")
print("upload output file")
output_file_object = f"input/{input_file_name}.json"
try:
S3_CLIENT.upload_file(input_to_pipeline_filename, bucket, output_file_object)
except Exception as e:
print(f"{func}: Failed to upload file to S3: {bucket}/{output_file_object}")
raise e
def process_splunk_input(event, context):
'''
Read input file and split in chunks
'''
global S3_CLIENT
global CHUNK_SIZE
func = "process_splunk_input"
bucket = event["Records"][0]["s3"]["bucket"]["name"]
input_file_object = urllib.parse.unquote_plus(event["Records"][0]["s3"]["object"]["key"], encoding="utf-8")
input_file = "/tmp/input.json"
clear_temp_dir()
try:
print(f"{func}: Download input file: {bucket}/{input_file_object}")
S3_CLIENT.download_file(bucket, input_file_object, input_file)
except Exception as e:
print(f"{func}: Failed to download file from S3: {bucket}/{input_file_object}")
raise e
print(f"{func}: Download completed")
chunks_of_large_input_file = create_chunk_for_large_input_file(input_file)
input_file_name = input_file_object.split("/")[-1].split(".")[0]
input_file_splits_length_json = {"count": len(chunks_of_large_input_file)}
input_file_splits_length_json_filename = f"splunk_input/{SCRATCH_DIR}/count/{input_file_name}/split_length.json"
temp_input_file_splits_length_json_filename = f"/tmp/split_length.json"
json.dump(input_file_splits_length_json, open(temp_input_file_splits_length_json_filename, "w"))
try:
S3_CLIENT.upload_file(temp_input_file_splits_length_json_filename, bucket, input_file_splits_length_json_filename)
except Exception as e:
print(f"{func}: Failed to save file to S3: {bucket}/{input_file_splits_length_json_filename}")
raise e
print(f"{func}: Upload chunks. Number of chunks: {len(chunks_of_large_input_file)}")
for i, chunk_of_large_input_file in enumerate(chunks_of_large_input_file, start=1):
output_file_object = f"splunk_input/{SCRATCH_DIR}/chunk/{input_file_name}/split_{i}.json"
try:
S3_CLIENT.upload_file(chunk_of_large_input_file, bucket, output_file_object)
except Exception as e:
print(f"{func}: Failed to save file to S3: {bucket}/{output_file_object}")
raise e
print(f"{func}: Upload completed")
def create_chunk_for_large_input_file(temp_input_file):
'''
Create chunks for a large input file
Returns:
List of split file names
'''
global CHUNK_SIZE
global BUF_SIZE
global TEMP_INPUT_DIR
split_files = []
with open(temp_input_file, 'rb') as f:
split_files = []
item = 1
input_list_iter = ijson.items(f, 'item', use_float=True, buf_size=BUF_SIZE)
while True:
input_list = list(islice(input_list_iter, CHUNK_SIZE))
split_filename = TEMP_INPUT_DIR + "input" + '_' + str(item) + '.json'
if not input_list:
break
with open(split_filename, 'w') as outfile:
for alert in input_list:
outfile.write(json.dumps(alert) + "\n")
split_files.append(split_filename)
item += 1
del input_list
gc.collect()
del input_list_iter
gc.collect()
return split_files
def clear_temp_dir():
rm_list = glob.glob("/tmp/**", recursive=True)
for f in rm_list:
if os.path.isfile(f):
os.remove(f)
Handler: index.lambda_handler
Runtime: python3.11
MemorySize: 3008
EphemeralStorage:
Size: 10240
Timeout: 900
Role: !GetAtt LambdaRole.Arn
Tracing: Active
Layers:
- !FindInMap
- RegionMap
- !Ref AWS::Region
- lambdaLayer
Environment:
Variables:
chunk_size: "5000"
Events:
S3ObjectCreated:
Type: S3
Properties:
Bucket: !Ref Bucket
Events: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: prefix
Value: splunk_input/input/
- Name: suffix
Value: .json
S3ObjectCreatedTransformed:
Type: S3
Properties:
Bucket: !Ref Bucket
Events: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: prefix
Value: splunk_input/scratch/transformed/
- Name: suffix
Value: .json
splunkInputLogGroup:
Type: AWS::Logs::LogGroup
DeletionPolicy: Retain
Properties:
LogGroupName: !Sub /aws/lambda/${splunkInput}
splunkInputLambdaEventInvokeConfig:
Type: AWS::Lambda::EventInvokeConfig
Properties:
FunctionName: !Ref splunkInput
MaximumRetryAttempts: 0
Qualifier: $LATEST
vrlLambda:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Ref VRLLambdaFunctionName
Description: !Sub
- Stack ${AWS::StackName} Function ${ResourceName}
- ResourceName: vrlLambda
ImageUri: !Ref VRLLambdaImage
PackageType: Image
MemorySize: 3008
EphemeralStorage:
Size: 10240
Timeout: 900
Role: !GetAtt LambdaRole.Arn
Tracing: Active
Environment:
Variables:
vrl_program_bucket: !Ref BucketName
vrl_program_s3_key: "splunk_input/program/program.vrl"
Events:
S3ObjectCreated:
Type: S3
Properties:
Bucket: !Ref Bucket
Events: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: prefix
Value: splunk_input/scratch/chunk/
- Name: suffix
Value: .json
vrlLambdaLogGroup:
Type: AWS::Logs::LogGroup
DeletionPolicy: Retain
Properties:
LogGroupName: !Sub /aws/lambda/${vrlLambda}
vrlLambdaLambdaEventInvokeConfig:
Type: AWS::Lambda::EventInvokeConfig
Properties:
FunctionName: !Ref vrlLambda
MaximumRetryAttempts: 0
Qualifier: $LATEST
enrichWithTechnique:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Ref EnrichTechFunctionName
Description: !Sub
- Stack ${AWS::StackName} Function ${ResourceName}
- ResourceName: enrichWithTechnique
InlineCode: |
'''
Chunk input file, sanititze in required format, encode attributes, encode node_features if present, generate internal id.
Create batch transform job for technique classification.
Input: User input file
'''
import os
import sys
import subprocess
import gc
from datetime import datetime, timezone
from dateutil import parser
import urllib
import uuid
import json
import glob
from itertools import islice
import sqlite3
from contextlib import closing
import boto3
from botocore.exceptions import ClientError
import pandas as pd
import numpy as np
# Install ijson pip library to handle large json input files
os.makedirs("/tmp/pylib", exist_ok=True)
subprocess.call('pip install ijson==3.3.0 -t /tmp/pylib/ --no-cache-dir'.split(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)