-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.yaml
More file actions
894 lines (843 loc) · 34 KB
/
template.yaml
File metadata and controls
894 lines (843 loc) · 34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
AWSTemplateFormatVersion: '2010-09-09'
Description: >
AttachmentAV Bucket Scan - Automatically scans files uploaded to an S3 bucket for malware using the AttachmentAV API.
This template creates Lambda functions to initiate scans and handle results, with configurable trigger strategies
(S3 Event or EventBridge), object tagging, and automatic deletion of infected files.
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: AttachmentAV Configuration
Parameters:
- ApiKeyParameterName
- ApiUrl
- TenantId
- Label:
default: Trigger Configuration
Parameters:
- TriggerStrategy
- S3KeyPrefix
- S3KeySuffix
- Label:
default: Scan Result Handling
Parameters:
- TagObjectWithScanResult
- DeleteInfectedObject
ParameterLabels:
ApiKeyParameterName:
default: API Key Parameter Name
ApiUrl:
default: API URL
TenantId:
default: Tenant ID
TriggerStrategy:
default: Trigger Strategy
S3KeyPrefix:
default: S3 Key Prefix Filter
S3KeySuffix:
default: S3 Key Suffix Filter
TagObjectWithScanResult:
default: Tag Objects with Scan Results
DeleteInfectedObject:
default: Delete Infected Objects
Parameters:
ApiKeyParameterName:
Description: SSM Parameter Store parameter name containing the attachmentAV API key. Must be a SecureString parameter.
Type: String
TriggerStrategy:
Description: Strategy for triggering the scanner Lambda
Type: String
Default: S3_EVENT
AllowedValues:
- S3_EVENT
- EVENTBRIDGE
TagObjectWithScanResult:
Description: Whether to tag S3 objects with scan results
Type: String
Default: "true"
AllowedValues:
- "true"
- "false"
DeleteInfectedObject:
Description: Whether to delete infected S3 objects. If true, infected files will be automatically deleted from S3
Type: String
Default: "false"
AllowedValues:
- "true"
- "false"
S3KeyPrefix:
Description: Optional S3 key prefix filter for triggering scans. Only objects with keys starting with this prefix will trigger scans.
Type: String
Default: ""
S3KeySuffix:
Description: Optional S3 key suffix filter for triggering scans. Only objects with keys ending with this suffix will trigger scans.
Type: String
Default: ""
ApiUrl:
Description: The attachmentAV API base URL
Type: String
Default: https://eu.developer.attachmentav.com
TenantId:
Description: The attachmentAV tenant id. If provided, all incoming callback events are verified.
Type: String
Default: ""
Conditions:
HasTagObjectWithScanResult: !Equals
- !Ref TagObjectWithScanResult
- "true"
HasDeleteInfectedObject: !Equals
- !Ref DeleteInfectedObject
- "true"
UsesS3Event: !Equals
- !Ref TriggerStrategy
- S3_EVENT
UsesEventBridge: !Equals
- !Ref TriggerStrategy
- EVENTBRIDGE
HasS3KeyPrefix: !Not
- !Equals
- !Ref S3KeyPrefix
- ""
HasS3KeySuffix: !Not
- !Equals
- !Ref S3KeySuffix
- ""
HasS3KeyFilter: !Or
- !Condition HasS3KeyPrefix
- !Condition HasS3KeySuffix
HasTenantId: !Not
- !Equals
- !Ref TenantId
- ""
Resources:
CallbackFunction:
Type: AWS::Lambda::Function
DependsOn:
- CallbackFunctionRole
Properties:
Code:
ZipFile: |
// ../lib/index.CallbackFunction.ts
import { S3Client, DeleteObjectCommand, PutObjectTaggingCommand } from "@aws-sdk/client-s3";
import { createPublicKey, createVerify } from "node:crypto";
var s3Client = new S3Client({});
var TAG_OBJECT_WITH_SCAN_RESULT = process.env.TAG_OBJECT_WITH_SCAN_RESULT === "true";
var DELETE_INFECTED_OBJECT = process.env.DELETE_INFECTED_OBJECT === "true";
var TENANT_ID = process.env.TENANT_ID;
var SIGNATURE_TOLERANCE_IN_MILLIS = 5 * 60 * 1e3;
var PUBLIC_KEY_PEM = `-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAyLoZzjo1cQV9ZN2TH/alrxWiQ3u/ndT0HMrLMdBTVO3Tz1nUjLt6
SqKZsN8dQhvPoEjfyhCTEg7MPWopG3n0cf3NRxtoeXy/Z62b1zdUd426kMuKOQP8
Yy6cxa/RtK2tkHCnTGxjfvNmMK+m68sFmsilR88LnIN71my4cG8bIDGDftWublvK
AEOWhxSECYn1XEtyrQL5lm8HFnHdE9ys56xTJkdr5Mmkvanrnd/hXzTHzjruGcLv
bjciI82+Z335AzYgJcnmH4/zsBuyPL2FJSfQF9NsPaTJuQgkw1usAKBQcujcEriY
UDNWgTe1a+LOnCEMb+9mAYw8lMRYRd3CBwIDAQAB
-----END RSA PUBLIC KEY-----`;
function verify(unixtimeInMillis, publicKeyPEM, timestamp, tenantId, callbackUrl, body, signature) {
const publicKey = createPublicKey({
key: publicKeyPEM,
format: "pem",
type: "pkcs1"
});
const verify2 = createVerify("sha256");
verify2.update(timestamp);
verify2.update(".");
verify2.update(tenantId);
verify2.update(".");
verify2.update(callbackUrl);
verify2.update(".");
verify2.update(body);
verify2.end();
const valid = verify2.verify(publicKey, signature, "hex");
return valid && Math.abs(unixtimeInMillis - parseInt(timestamp, 10)) <= SIGNATURE_TOLERANCE_IN_MILLIS;
}
function logResult(bucket, key, versionId, result) {
console.log("Scan Results:", JSON.stringify({
bucket,
key,
versionId,
status: result.status,
finding: result.finding || "none",
size: result.size,
realFileType: result.realfiletype,
downloadTime: result.download_time,
scanTime: result.scan_time,
timestamp: (/* @__PURE__ */ new Date()).toISOString()
}, null, 2));
if (result.status === "clean") {
console.log(`\u2713 File is CLEAN - No threats detected`);
console.log(` File type: ${result.realfiletype}`);
console.log(` File size: ${result.size} bytes`);
} else if (result.status === "infected") {
console.warn(`\u26A0 File is INFECTED - Malware detected!`);
console.warn(` Threat: ${result.finding || "Unknown"}`);
console.warn(` File type: ${result.realfiletype}`);
console.warn(` File size: ${result.size} bytes`);
} else {
console.warn(`\u26A0 Scan status UNKNOWN - Unable to determine file status`);
console.warn(` File type: ${result.realfiletype}`);
console.warn(` File size: ${result.size} bytes`);
}
}
async function tagObjectWithResult(bucket, key, versionId, result) {
const objectRef = versionId ? `s3://${bucket}/${key} (version: ${versionId})` : `s3://${bucket}/${key}`;
console.log(`Tagging object with scan results: ${objectRef}`);
try {
await s3Client.send(
new PutObjectTaggingCommand({
Bucket: bucket,
Key: key,
...versionId ? { VersionId: versionId } : {},
Tagging: {
TagSet: [
{ Key: "ScanStatus", Value: result.status },
{ Key: "ScanFinding", Value: result.finding || "none" },
{ Key: "ScanTimestamp", Value: (/* @__PURE__ */ new Date()).toISOString() }
]
}
})
);
console.log(`\u2713 Successfully tagged object with scan results`);
} catch (tagError) {
console.error(`Failed to tag object:`, tagError);
}
}
async function deleteObject(bucket, key, versionId) {
console.warn(`Deleting infected file: s3://${bucket}/${key} (version: ${versionId || ""}`);
try {
await s3Client.send(
new DeleteObjectCommand({
Bucket: bucket,
Key: key,
...versionId ? { VersionId: versionId } : {}
})
);
console.warn(`\u2713 Successfully deleted infected file`);
} catch (deleteError) {
console.error(`Failed to delete infected file:`, deleteError);
}
}
var handler = async (event) => {
console.debug(`Received callback from attachmentAV: ${JSON.stringify(event, null, 2)}`);
if (!event.body) {
console.error("No body in callback request");
return {
statusCode: 400,
body: JSON.stringify({ error: "Missing request body" })
};
}
if (TENANT_ID) {
const attachmentAVTimestamp = event.headers["x-timestamp"];
const attachmentAVSignature = event.headers["x-signature"];
if (!attachmentAVTimestamp || !attachmentAVSignature) {
console.error("can not validate signature as timestamp or signature as missing");
return {
statusCode: 432,
body: JSON.stringify({ error: "callback signature validation failed: no timestamp or signature provided" })
};
}
const callbackUrl = `https://${event.requestContext.domainName}/`;
const isValidCallback = verify(Date.now(), PUBLIC_KEY_PEM, attachmentAVTimestamp, TENANT_ID, callbackUrl, event.body, attachmentAVSignature);
console.log(`signature verification result: ${isValidCallback ? "valid" : "invalid"}`);
if (!isValidCallback) {
console.error("callback signature validation failed");
return {
statusCode: 432,
body: JSON.stringify({ error: "callback signature validation failed" })
};
}
}
const result = JSON.parse(event.body);
const customData = result.custom_data ? JSON.parse(result.custom_data) : void 0;
const bucket = customData?.bucket;
const key = customData?.key;
const versionId = customData?.versionId;
if (!bucket || !key) {
console.error("Missing bucket or key in custom_data");
return {
statusCode: 400,
body: JSON.stringify({ error: "Missing bucket or key in custom_data" })
};
}
if (versionId) {
console.log(`Scan results for s3://${bucket}/${key} (version: ${versionId})`);
} else {
console.log(`Scan results for s3://${bucket}/${key}`);
}
logResult(bucket, key, versionId, result);
if (TAG_OBJECT_WITH_SCAN_RESULT) {
await tagObjectWithResult(bucket, key, versionId, result);
}
if (result.status === "infected" && DELETE_INFECTED_OBJECT) {
await deleteObject(bucket, key, versionId);
}
return {
statusCode: 200,
body: JSON.stringify({ message: "Scan results received and logged" })
};
};
export {
handler
};
Description: Handles and logs attachmentAV scan results
Environment:
Variables:
DELETE_INFECTED_OBJECT: !Ref DeleteInfectedObject
TAG_OBJECT_WITH_SCAN_RESULT: !Ref TagObjectWithScanResult
TENANT_ID: !Ref TenantId
Handler: index.handler
MemorySize: 256
Role: !GetAtt CallbackFunctionRole.Arn
Runtime: nodejs24.x
Timeout: 10
CallbackFunctionUrl:
Type: AWS::Lambda::Url
Properties:
AuthType: NONE
TargetFunctionArn: !GetAtt CallbackFunction.Arn
CallbackFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Version: "2012-10-17"
ManagedPolicyArns:
- !Join
- ""
- - 'arn:'
- !Ref AWS::Partition
- :iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
CallbackFunctionTaggingPolicy:
Type: AWS::IAM::Policy
Condition: HasTagObjectWithScanResult
Properties:
PolicyDocument:
Statement:
- Action: s3:ListBucket
Effect: Allow
Resource: !GetAtt Bucket.Arn
- Action:
- s3:PutObjectTagging
- s3:PutObjectVersionTagging
Effect: Allow
Resource: !Join
- ""
- - !GetAtt Bucket.Arn
- /*
Version: "2012-10-17"
PolicyName: CallbackFunctionTaggingPolicy
Roles:
- !Ref CallbackFunctionRole
CallbackFunctionDeletePolicy:
Type: AWS::IAM::Policy
Condition: HasDeleteInfectedObject
Properties:
PolicyDocument:
Statement:
- Action: s3:DeleteObject*
Effect: Allow
Resource: !Join
- ""
- - !GetAtt Bucket.Arn
- /*
Version: "2012-10-17"
PolicyName: CallbackFunctionDeletePolicy
Roles:
- !Ref CallbackFunctionRole
CallbackFunctionInvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt CallbackFunction.Arn
InvokedViaFunctionUrl: true
Principal: '*'
CallbackFunctionUrlPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunctionUrl
FunctionName: !GetAtt CallbackFunction.Arn
FunctionUrlAuthType: NONE
Principal: '*'
DownloadAccessKey:
Type: AWS::IAM::AccessKey
Properties:
UserName: !Ref DownloadUser
DownloadAccessKeyIdParameter:
Type: AWS::SSM::Parameter
Properties:
Description: Access Key ID for attachmentAV presigned URL generation
Name: !Sub '/${AWS::StackName}/attachmentav/presign-download-user/access-key-id'
Type: String
Value: !Ref DownloadAccessKey
DownloadSecretAccessKeyParameter:
Type: AWS::SSM::Parameter
Properties:
Description: Secret Access Key for attachmentAV presigned URL generation
Name: !Sub '/${AWS::StackName}/attachmentav/presign-download-user/secret-access-key'
Type: String
Value: !GetAtt DownloadAccessKey.SecretAccessKey
DownloadUser:
Type: AWS::IAM::User
DownloadUserPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Statement:
- Action:
- s3:GetObject*
- s3:GetBucket*
- s3:List*
Effect: Allow
Resource:
- !GetAtt Bucket.Arn
- !Join
- ""
- - !GetAtt Bucket.Arn
- /*
Version: "2012-10-17"
PolicyName: DownloadUserPolicy
Users:
- !Ref DownloadUser
ScannerFunction:
Type: AWS::Lambda::Function
DependsOn:
- ScannerFunctionPolicy
- ScannerFunctionRole
Properties:
Code:
ZipFile: |
// ../lib/index.ScannerFunction.ts
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
var PRESIGNED_URL_EXPIRATION_SECONDS = 3600;
var API_URL = process.env.ATTACHMENTAV_API_URL || "https://eu.developer.attachmentav.com";
var API_KEY_PARAMETER = process.env.ATTACHMENTAV_API_KEY_PARAMETER;
var CALLBACK_URL = process.env.CALLBACK_URL;
var AWS_ACCESS_KEY_ID_PARAMETER = process.env.AWS_ACCESS_KEY_ID_PARAMETER;
var AWS_SECRET_ACCESS_KEY_PARAMETER = process.env.AWS_SECRET_ACCESS_KEY_PARAMETER;
var ssmClient = new SSMClient({});
var attachmentAVApiKey;
var awsCredentials;
async function getAttachmentAVApiKey() {
const parameterResponse = await ssmClient.send(
new GetParameterCommand({
Name: API_KEY_PARAMETER,
WithDecryption: true
})
);
const apiKey = parameterResponse.Parameter?.Value;
if (!apiKey) {
throw new Error(`Failed to retrieve API key from parameter: ${API_KEY_PARAMETER}`);
}
return apiKey;
}
async function getAWSCredentials() {
if (!AWS_ACCESS_KEY_ID_PARAMETER || !AWS_SECRET_ACCESS_KEY_PARAMETER) {
throw new Error("AWS credential parameter names are not set");
}
const accessKeyIdResponse = await ssmClient.send(
new GetParameterCommand({
Name: AWS_ACCESS_KEY_ID_PARAMETER,
WithDecryption: true
})
);
const accessKeyId = accessKeyIdResponse.Parameter?.Value;
if (!accessKeyId) {
throw new Error(`Failed to retrieve Access Key ID from parameter: ${AWS_ACCESS_KEY_ID_PARAMETER}`);
}
const secretAccessKeyResponse = await ssmClient.send(
new GetParameterCommand({
Name: AWS_SECRET_ACCESS_KEY_PARAMETER,
WithDecryption: true
})
);
const secretAccessKey = secretAccessKeyResponse.Parameter?.Value;
if (!secretAccessKey) {
throw new Error(`Failed to retrieve Secret Access Key from parameter: ${AWS_SECRET_ACCESS_KEY_PARAMETER}`);
}
return {
accessKeyId,
secretAccessKey
};
}
async function startFileScan(s3Client, callbackUrl, bucket, key, versionId) {
const getObjectCommand = new GetObjectCommand({
Bucket: bucket,
Key: key,
...versionId && { VersionId: versionId }
});
const presignedUrl = await getSignedUrl(s3Client, getObjectCommand, {
expiresIn: PRESIGNED_URL_EXPIRATION_SECONDS
});
console.log("Generated presigned URL using IAM User credentials");
const customData = {
bucket,
key,
...versionId && { versionId }
};
const requestBody = {
download_url: presignedUrl,
callback_url: callbackUrl,
custom_data: JSON.stringify(customData)
};
const apiEndpoint = `${API_URL}/v1/scan/async/download`;
console.log(`Calling attachmentAV API: ${apiEndpoint}`);
const response = await fetch(apiEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": attachmentAVApiKey
},
body: JSON.stringify(requestBody)
});
if (response.status === 204) {
console.log(`Successfully submitted scan request for s3://${bucket}/${key} (version: ${versionId || ""})`);
} else {
const responseText = await response.text();
console.error(`Unexpected response status: ${response.status}`);
console.error(`Response body: ${responseText}`);
throw new Error(`attachmentAV API returned status ${response.status}: ${responseText}`);
}
}
var handler = async (event) => {
console.log("Received S3 event:", JSON.stringify(event, null, 2));
if (!API_KEY_PARAMETER) {
throw new Error("ATTACHMENTAV_API_KEY_PARAMETER environment variable is not set");
}
if (!CALLBACK_URL) {
throw new Error("CALLBACK_URL environment variable is not set");
}
if (!AWS_ACCESS_KEY_ID_PARAMETER || !AWS_SECRET_ACCESS_KEY_PARAMETER) {
throw new Error("AWS credential parameter environment variables are not set");
}
if (!attachmentAVApiKey) {
attachmentAVApiKey = await getAttachmentAVApiKey();
}
if (!awsCredentials) {
awsCredentials = await getAWSCredentials();
}
const s3Client = new S3Client({
credentials: {
accessKeyId: awsCredentials.accessKeyId,
secretAccessKey: awsCredentials.secretAccessKey
}
});
if (event.Records) {
console.log("event is S3 event notification - processing records");
for (const record of event.Records) {
const bucket = record.s3.bucket.name;
const key = record.s3.object.key;
const versionId = record.s3.object.versionId;
console.log(`Processing file: s3://${bucket}/${key} (version: ${versionId || ""})`);
try {
await startFileScan(s3Client, CALLBACK_URL, bucket, key, versionId);
} catch (error) {
console.error(`Error processing file s3://${bucket}/${key} (version: ${versionId || ""}):`, error);
throw error;
}
}
} else {
console.log("event is EventBridge S3 event");
const eventBridgeEvent = event;
const bucket = eventBridgeEvent.detail.bucket.name;
const key = eventBridgeEvent.detail.object.key;
const versionId = eventBridgeEvent.detail.object["version-id"];
console.log(`Processing file: s3://${bucket}/${key} (version: ${versionId || ""})`);
try {
await startFileScan(s3Client, CALLBACK_URL, bucket, key, versionId);
} catch (error) {
console.error(`Error processing file s3://${bucket}/${key} (version: ${versionId || ""}):`, error);
throw error;
}
}
};
export {
handler
};
Description: Initiates attachmentAV scans for S3 objects
Environment:
Variables:
ATTACHMENTAV_API_KEY_PARAMETER: !Ref ApiKeyParameterName
ATTACHMENTAV_API_URL: !Ref ApiUrl
AWS_ACCESS_KEY_ID_PARAMETER: !Ref DownloadAccessKeyIdParameter
AWS_SECRET_ACCESS_KEY_PARAMETER: !Ref DownloadSecretAccessKeyParameter
CALLBACK_URL: !GetAtt CallbackFunctionUrl.FunctionUrl
Handler: index.handler
MemorySize: 256
Role: !GetAtt ScannerFunctionRole.Arn
Runtime: nodejs24.x
Timeout: 30
ScannerFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Version: "2012-10-17"
ManagedPolicyArns:
- !Join
- ""
- - 'arn:'
- !Ref AWS::Partition
- :iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
ScannerFunctionPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Statement:
- Action: ssm:GetParameter
Effect: Allow
Resource:
- !Sub 'arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter${ApiKeyParameterName}'
- !Sub 'arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter${DownloadAccessKeyIdParameter}'
- !Sub 'arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter${DownloadSecretAccessKeyParameter}'
Version: "2012-10-17"
PolicyName: ScannerFunctionPolicy
Roles:
- !Ref ScannerFunctionRole
ScannerRule:
Type: AWS::Events::Rule
Condition: UsesEventBridge
Properties:
Description: Trigger attachmentAV scanner on S3 object creation
EventPattern:
detail:
bucket:
name:
- !Ref Bucket
object: !If
- HasS3KeyFilter
- key:
- wildcard: !Sub '${S3KeyPrefix}*${S3KeySuffix}'
- !Ref AWS::NoValue
detail-type:
- Object Created
source:
- aws.s3
State: ENABLED
Targets:
- Arn: !GetAtt ScannerFunction.Arn
Id: Target0
ScannerRulePermission:
Type: AWS::Lambda::Permission
Condition: UsesEventBridge
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt ScannerFunction.Arn
Principal: events.amazonaws.com
SourceArn: !GetAtt ScannerRule.Arn
Bucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
BucketNotificationPermission:
Type: AWS::Lambda::Permission
Condition: UsesS3Event
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt ScannerFunction.Arn
Principal: s3.amazonaws.com
SourceAccount: !Ref AWS::AccountId
SourceArn: !GetAtt Bucket.Arn
# This custom resource is necessary to avoid circular dependencies between the S3 Bucket and Scanner Function
BucketNotifications:
Type: Custom::S3BucketNotifications
Properties:
BucketName: !Ref Bucket
Managed: true
NotificationConfiguration: !If
- UsesEventBridge
- EventBridgeConfiguration: {}
- !If
- HasS3KeyFilter
- LambdaFunctionConfigurations:
- Events:
- s3:ObjectCreated:*
Filter:
Key:
FilterRules: !If
- HasS3KeyPrefix
- !If
- HasS3KeySuffix
- - Name: prefix
Value: !Ref S3KeyPrefix
- Name: suffix
Value: !Ref S3KeySuffix
- - Name: prefix
Value: !Ref S3KeyPrefix
- - Name: suffix
Value: !Ref S3KeySuffix
LambdaFunctionArn: !GetAtt ScannerFunction.Arn
- LambdaFunctionConfigurations:
- Events:
- s3:ObjectCreated:*
LambdaFunctionArn: !GetAtt ScannerFunction.Arn
ServiceToken: !GetAtt CustomBucketNotificationsHandler.Arn
SkipDestinationValidation: false
CustomBucketNotificationsHandler:
Type: AWS::Lambda::Function
DependsOn:
- CustomBucketNotificationHandlerPolicy
- CustomBucketNotificationHandlerRole
Properties:
Code:
# Note: Code is taken from CDK
ZipFile: |
import boto3 # type: ignore
import json
import logging
import urllib.request
s3 = boto3.client("s3")
EVENTBRIDGE_CONFIGURATION = 'EventBridgeConfiguration'
CONFIGURATION_TYPES = ["TopicConfigurations", "QueueConfigurations", "LambdaFunctionConfigurations"]
def handler(event: dict, context):
response_status = "SUCCESS"
error_message = ""
try:
props = event["ResourceProperties"]
notification_configuration = props["NotificationConfiguration"]
managed = props.get('Managed', 'true').lower() == 'true'
skipDestinationValidation = props.get('SkipDestinationValidation', 'false').lower() == 'true'
stack_id = event['StackId']
old = event.get("OldResourceProperties", {}).get("NotificationConfiguration", {})
if managed:
config = handle_managed(event["RequestType"], notification_configuration)
else:
config = handle_unmanaged(props["BucketName"], stack_id, event["RequestType"], notification_configuration, old)
s3.put_bucket_notification_configuration(Bucket=props["BucketName"], NotificationConfiguration=config, SkipDestinationValidation=skipDestinationValidation)
except Exception as e:
logging.exception("Failed to put bucket notification configuration")
response_status = "FAILED"
error_message = f"Error: {str(e)}. "
finally:
submit_response(event, context, response_status, error_message)
def handle_managed(request_type, notification_configuration):
if request_type == 'Delete':
return {}
return notification_configuration
def handle_unmanaged(bucket, stack_id, request_type, notification_configuration, old):
def get_id(n):
n['Id'] = ''
sorted_notifications = sort_filter_rules(n)
strToHash=json.dumps(sorted_notifications, sort_keys=True).replace('"Name": "prefix"', '"Name": "Prefix"').replace('"Name": "suffix"', '"Name": "Suffix"')
return f"{stack_id}-{hash(strToHash)}"
def with_id(n):
n['Id'] = get_id(n)
return n
external_notifications = {}
existing_notifications = s3.get_bucket_notification_configuration(Bucket=bucket)
for t in CONFIGURATION_TYPES:
if request_type == 'Update':
old_incoming_ids = [get_id(n) for n in old.get(t, [])]
external_notifications[t] = [n for n in existing_notifications.get(t, []) if not get_id(n) in old_incoming_ids]
elif request_type == 'Delete':
external_notifications[t] = [n for n in existing_notifications.get(t, []) if not n['Id'].startswith(f"{stack_id}-")]
elif request_type == 'Create':
external_notifications[t] = [n for n in existing_notifications.get(t, [])]
if EVENTBRIDGE_CONFIGURATION in existing_notifications:
external_notifications[EVENTBRIDGE_CONFIGURATION] = existing_notifications[EVENTBRIDGE_CONFIGURATION]
if request_type == 'Delete':
return external_notifications
notifications = {}
for t in CONFIGURATION_TYPES:
external = external_notifications.get(t, [])
incoming = [with_id(n) for n in notification_configuration.get(t, [])]
notifications[t] = external + incoming
if EVENTBRIDGE_CONFIGURATION in notification_configuration:
notifications[EVENTBRIDGE_CONFIGURATION] = notification_configuration[EVENTBRIDGE_CONFIGURATION]
elif EVENTBRIDGE_CONFIGURATION in external_notifications:
notifications[EVENTBRIDGE_CONFIGURATION] = external_notifications[EVENTBRIDGE_CONFIGURATION]
return notifications
def submit_response(event: dict, context, response_status: str, error_message: str):
response_body = json.dumps(
{
"Status": response_status,
"Reason": f"{error_message}See the details in CloudWatch Log Stream: {context.log_stream_name}",
"PhysicalResourceId": event.get("PhysicalResourceId") or event["LogicalResourceId"],
"StackId": event["StackId"],
"RequestId": event["RequestId"],
"LogicalResourceId": event["LogicalResourceId"],
"NoEcho": False,
}
).encode("utf-8")
headers = {"content-type": "", "content-length": str(len(response_body))}
try:
req = urllib.request.Request(url=event["ResponseURL"], headers=headers, data=response_body, method="PUT")
with urllib.request.urlopen(req) as response:
print(response.read().decode("utf-8"))
print("Status code: " + response.reason)
except Exception as e:
print("send(..) failed executing request.urlopen(..): " + str(e))
def sort_filter_rules(json_obj):
if not isinstance(json_obj, dict):
return json_obj
for key, value in json_obj.items():
if isinstance(value, dict):
json_obj[key] = sort_filter_rules(value)
elif isinstance(value, list):
json_obj[key] = [sort_filter_rules(item) for item in value]
if "Filter" in json_obj and "Key" in json_obj["Filter"] and "FilterRules" in json_obj["Filter"]["Key"]:
filter_rules = json_obj["Filter"]["Key"]["FilterRules"]
sorted_filter_rules = sorted(filter_rules, key=lambda x: x["Name"])
json_obj["Filter"]["Key"]["FilterRules"] = sorted_filter_rules
return json_obj
Description: AWS CloudFormation handler for Custom::S3BucketNotifications resources
Handler: index.handler
Role: !GetAtt CustomBucketNotificationHandlerRole.Arn
Runtime: python3.13
Timeout: 300
CustomBucketNotificationHandlerRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Version: "2012-10-17"
ManagedPolicyArns:
- !Join
- ""
- - 'arn:'
- !Ref AWS::Partition
- :iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
CustomBucketNotificationHandlerPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Statement:
- Action: s3:PutBucketNotification
Effect: Allow
Resource: !GetAtt Bucket.Arn
Version: "2012-10-17"
PolicyName: CustomBucketNotificationHandlerPolicy
Roles:
- !Ref CustomBucketNotificationHandlerRole
Outputs:
BucketName:
Description: Name of the S3 bucket being monitored for malware scanning
Value: !Ref Bucket
Export:
Name: !Sub '${AWS::StackName}-BucketName'
ScannerFunctionArn:
Description: ARN of the Lambda function that initiates scans
Value: !GetAtt ScannerFunction.Arn
Export:
Name: !Sub '${AWS::StackName}-ScannerFunctionArn'
CallbackFunctionArn:
Description: ARN of the Lambda function that handles scan results
Value: !GetAtt CallbackFunction.Arn
Export:
Name: !Sub '${AWS::StackName}-CallbackFunctionArn'
TriggerStrategy:
Description: The trigger strategy being used (S3_EVENT or EVENTBRIDGE)
Value: !Ref TriggerStrategy