forked from bluesentry/bucket-antivirus-function
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scan.py
293 lines (252 loc) · 10.2 KB
/
scan.py
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
# -*- coding: utf-8 -*-
# Upside Travel, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import json
import base64
import os
from urllib.parse import unquote_plus
from distutils.util import strtobool
import boto3
import clamav
import metrics
from common import AV_DEFINITION_S3_BUCKET
from common import AV_DEFINITION_S3_PREFIX
from common import AV_DELETE_INFECTED_FILES
from common import AV_PROCESS_ORIGINAL_VERSION_ONLY
from common import AV_SCAN_START_METADATA
from common import AV_SCAN_START_SNS_ARN
from common import AV_SIGNATURE_METADATA
from common import AV_STATUS_CLEAN
from common import AV_STATUS_INFECTED
from common import AV_STATUS_METADATA
from common import AV_STATUS_SNS_ARN
from common import AV_STATUS_SNS_PUBLISH_CLEAN
from common import AV_STATUS_SNS_PUBLISH_INFECTED
from common import AV_TIMESTAMP_METADATA
from common import create_dir
from common import get_timestamp
def event_object(event, event_source="s3"):
# SNS events are slightly different
if event_source.upper() == "SNS":
event = json.loads(event["Records"][0]["Sns"]["Message"])
# Break down the record
records = event["Records"]
if len(records) == 0:
raise Exception("No records found in event!")
record = records[0]
s3_obj = record["s3"]
# Get the bucket name
if "bucket" not in s3_obj:
raise Exception("No bucket found in event!")
bucket_name = s3_obj["bucket"].get("name", None)
# Get the key name
if "object" not in s3_obj:
raise Exception("No key found in event!")
key_name = s3_obj["object"].get("key", None)
sse_customer_key = s3_obj["object"].get("sseCustomerKey", None)
if key_name:
key_name = unquote_plus(key_name)
# Ensure both bucket and key exist
if (not bucket_name) or (not key_name):
raise Exception("Unable to retrieve object from event.\n{}".format(event))
# Create and return the object
s3 = boto3.resource("s3")
return {"s3_object": s3.Object(bucket_name, key_name), "sse_customer_key": sse_customer_key}
def verify_s3_object_version(s3, s3_object):
# validate that we only process the original version of a file, if asked to do so
# security check to disallow processing of a new (possibly infected) object version
# while a clean initial version is getting processed
# downstream services may consume latest version by mistake and get the infected version instead
bucket_versioning = s3.BucketVersioning(s3_object.bucket_name)
if bucket_versioning.status == "Enabled":
bucket = s3.Bucket(s3_object.bucket_name)
versions = list(bucket.object_versions.filter(Prefix=s3_object.key))
if len(versions) > 1:
raise Exception(
"Detected multiple object versions in %s.%s, aborting processing"
% (s3_object.bucket_name, s3_object.key)
)
else:
# misconfigured bucket, left with no or suspended versioning
raise Exception(
"Object versioning is not enabled in bucket %s" % s3_object.bucket_name
)
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
def get_local_path(s3_object, local_prefix):
return os.path.join(local_prefix, s3_object.bucket_name, remove_prefix(s3_object.key, "/"))
def delete_s3_object(s3_object):
try:
s3_object.delete()
except Exception:
raise Exception(
"Failed to delete infected file: %s.%s"
% (s3_object.bucket_name, s3_object.key)
)
else:
print("Infected file deleted: %s.%s" % (s3_object.bucket_name, s3_object.key))
def set_av_metadata(s3_object, scan_result, scan_signature, timestamp):
content_type = s3_object.content_type
metadata = s3_object.metadata
metadata[AV_SIGNATURE_METADATA] = scan_signature
metadata[AV_STATUS_METADATA] = scan_result
metadata[AV_TIMESTAMP_METADATA] = timestamp
s3_object.copy(
{"Bucket": s3_object.bucket_name, "Key": s3_object.key},
ExtraArgs={
"ContentType": content_type,
"Metadata": metadata,
"MetadataDirective": "REPLACE",
},
)
def set_av_tags(s3_client, s3_object, scan_result, scan_signature, timestamp):
curr_tags = s3_client.get_object_tagging(
Bucket=s3_object.bucket_name, Key=s3_object.key
)["TagSet"]
new_tags = copy.copy(curr_tags)
for tag in curr_tags:
if tag["Key"] in [
AV_SIGNATURE_METADATA,
AV_STATUS_METADATA,
AV_TIMESTAMP_METADATA,
]:
new_tags.remove(tag)
new_tags.append({"Key": AV_SIGNATURE_METADATA, "Value": scan_signature})
new_tags.append({"Key": AV_STATUS_METADATA, "Value": scan_result})
new_tags.append({"Key": AV_TIMESTAMP_METADATA, "Value": timestamp})
s3_client.put_object_tagging(
Bucket=s3_object.bucket_name, Key=s3_object.key, Tagging={"TagSet": new_tags}
)
def sns_start_scan(sns_client, s3_object, scan_start_sns_arn, timestamp):
message = {
"bucket": s3_object.bucket_name,
"key": s3_object.key,
"version": s3_object.version_id,
AV_SCAN_START_METADATA: True,
AV_TIMESTAMP_METADATA: timestamp,
}
sns_client.publish(
TargetArn=scan_start_sns_arn,
Message=json.dumps({"default": json.dumps(message)}),
MessageStructure="json",
)
def sns_scan_results(
sns_client, s3_object, sns_arn, scan_result, scan_signature, timestamp
):
# Don't publish if scan_result is CLEAN and CLEAN results should not be published
if scan_result == AV_STATUS_CLEAN and not str_to_bool(AV_STATUS_SNS_PUBLISH_CLEAN):
return
# Don't publish if scan_result is INFECTED and INFECTED results should not be published
if scan_result == AV_STATUS_INFECTED and not str_to_bool(
AV_STATUS_SNS_PUBLISH_INFECTED
):
return
message = {
"bucket": s3_object.bucket_name,
"key": s3_object.key,
"version": s3_object.version_id,
AV_SIGNATURE_METADATA: scan_signature,
AV_STATUS_METADATA: scan_result,
AV_TIMESTAMP_METADATA: get_timestamp(),
}
sns_client.publish(
TargetArn=sns_arn,
Message=json.dumps({"default": json.dumps(message)}),
MessageStructure="json",
MessageAttributes={
AV_STATUS_METADATA: {"DataType": "String", "StringValue": scan_result},
AV_SIGNATURE_METADATA: {
"DataType": "String",
"StringValue": scan_signature,
},
},
)
def decrypt_kms_data_key(kms_client, data_key):
if data_key == None:
return None
binary_data = base64.b64decode(data_key)
response = kms_client.decrypt(CiphertextBlob=binary_data)
return response[u'Plaintext']
def lambda_handler(event, context):
s3 = boto3.resource("s3")
s3_client = boto3.client("s3")
sns_client = boto3.client("sns")
kms_client = boto3.client("kms")
# Get some environment variables
ENV = os.getenv("ENV", "")
EVENT_SOURCE = os.getenv("EVENT_SOURCE", "S3")
start_time = get_timestamp()
print("Script starting at %s\n" % (start_time))
event_details = event_object(event, event_source=EVENT_SOURCE)
s3_object = event_details['s3_object']
sse_customer_plain_text_key = decrypt_kms_data_key(kms_client, event_details['sse_customer_key'])
if str_to_bool(AV_PROCESS_ORIGINAL_VERSION_ONLY):
verify_s3_object_version(s3, s3_object)
# Publish the start time of the scan
if AV_SCAN_START_SNS_ARN not in [None, ""]:
start_scan_time = get_timestamp()
sns_start_scan(sns_client, s3_object, AV_SCAN_START_SNS_ARN, start_scan_time)
file_path = get_local_path(s3_object, "/tmp")
create_dir(os.path.dirname(file_path))
extra_args_for_download = None
if sse_customer_plain_text_key != None:
extra_args_for_download = {'SSECustomerKey': sse_customer_plain_text_key, 'SSECustomerAlgorithm': 'AES256'}
s3_object.download_file(file_path, ExtraArgs=extra_args_for_download)
to_download = clamav.update_defs_from_s3(
s3_client, AV_DEFINITION_S3_BUCKET, AV_DEFINITION_S3_PREFIX
)
for download in to_download.values():
s3_path = download["s3_path"]
local_path = download["local_path"]
print("Downloading definition file %s from s3://%s" % (local_path, s3_path))
s3.Bucket(AV_DEFINITION_S3_BUCKET).download_file(s3_path, local_path)
print("Downloading definition file %s complete!" % (local_path))
scan_result, scan_signature = clamav.scan_file(file_path)
print(
"Scan of s3://%s resulted in %s\n"
% (os.path.join(s3_object.bucket_name, s3_object.key), scan_result)
)
result_time = get_timestamp()
# Set the properties on the object with the scan results
if "AV_UPDATE_METADATA" in os.environ:
set_av_metadata(s3_object, scan_result, scan_signature, result_time)
set_av_tags(s3_client, s3_object, scan_result, scan_signature, result_time)
# Publish the scan results
if AV_STATUS_SNS_ARN not in [None, ""]:
sns_scan_results(
sns_client,
s3_object,
AV_STATUS_SNS_ARN,
scan_result,
scan_signature,
result_time,
)
metrics.send(
env=ENV, bucket=s3_object.bucket_name, key=s3_object.key, status=scan_result
)
# Delete downloaded file to free up room on re-usable lambda function container
try:
os.remove(file_path)
except OSError:
pass
if str_to_bool(AV_DELETE_INFECTED_FILES) and scan_result == AV_STATUS_INFECTED:
delete_s3_object(s3_object)
stop_scan_time = get_timestamp()
print("Script finished at %s\n" % stop_scan_time)
return scan_result
def str_to_bool(s):
return bool(strtobool(str(s)))