-
Notifications
You must be signed in to change notification settings - Fork 70
/
server.js
406 lines (369 loc) · 11.5 KB
/
server.js
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
/*
* Copyright 2022 Google LLC
* 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
* https://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.
*/
const process = require('node:process');
// @ts-ignore -- TS7016: Could not find a declaration file
const clamd = require('clamdjs');
const express = require('express');
const {Storage} = require('@google-cloud/storage');
const {GoogleAuth} = require('google-auth-library');
const {logger} = require('./logger.js');
const pkgJson = require('./package.json');
const metrics = require('./metrics.js');
const util = require('node:util');
const execFile = util.promisify(require('node:child_process').execFile);
const {setTimeout} = require('timers/promises');
const {readAndVerifyConfig} = require('./config.js');
/** @typedef {import('./config.js').Config} Config */
/** @typedef {import('express').Request} Request */
/** @typedef {import('express').Response} Response */
const PORT = process.env.PORT || 8080;
const CLAMD_HOST = '127.0.0.1';
const CLAMD_PORT = 3310;
// 10 min timeout for scanning.
const CLAMD_TIMEOUT = 600000;
// Note: MAX_FILE_SIZE limits the size of files which are sent to th
// ClamAV Daemon.
//
// ClamAV itself has internal limits, which apply both to the total file
// size, and to the size of compressed files inside file containers.
// These are set in the clamd.conf file by bootstrap.sh
//
// Note scanning a 500MiB file can take 5 minutes, so ensure timeout is
// large enough.
const MAX_FILE_SIZE = 500000000; // 500MiB
/**
* Configuration object.
*
* Values are read from the JSON configuration file.
* See {@link readAndVerifyConfig}.
*
* @type {Config}
*/
const BUCKET_CONFIG = {
buckets: [],
ClamCvdMirrorBucket: '',
};
// Create Clients.
const app = express();
app.use(express.json());
/** @type {any} */
const scanner = clamd.createScanner(CLAMD_HOST, CLAMD_PORT);
const storage = new Storage({
userAgent: `cloud-solutions/${pkgJson.name}-usage-v${pkgJson.version}`,
});
const googleAuth = new GoogleAuth();
/**
* Route that is invoked by Cloud Run when a malware scan is requested
* for a document uploaded to GCS.
*
* For command line testing, use
*
* curl -d '{"kind": "storage#object","name":"test_file", "bucket": "BUCKET_NAME" }' -H "Content-Type: application/json" http://localhost:8080
*/
app.post('/', async (req, res) => {
// Sanity check required values.
switch (req.body.kind) {
case 'storage#object':
await handleGcsObject(req, res);
break;
case 'schedule#cvd_update':
await handleCvdUpdate(req, res);
break;
default:
handleErrorResponse(
res,
200,
`${JSON.stringify(req.body)} is not supported` +
'(kind must be storage#object or schedule#cvd_update',
);
break;
}
});
/**
* Handle a POST with a GCS object payload.
*
* @param {!Request} req The request payload
* @param {!Response} res The HTTP response object
*/
async function handleGcsObject(req, res) {
const file = req.body;
try {
if (!file?.name) {
handleErrorResponse(res, 200, `file name not specified in ${file}`);
return;
}
if (!file?.bucket) {
handleErrorResponse(res, 200, `bucket name not specified in ${file}`);
return;
}
const fileSize = parseInt(file.size);
if (fileSize > MAX_FILE_SIZE) {
handleErrorResponse(
res,
200,
`file gs://${file.bucket}/${file.name} too large for scanning at ${fileSize} bytes`,
file.bucket,
);
return;
}
const config = BUCKET_CONFIG.buckets.filter(
(c) => c.unscanned === file.bucket,
)[0];
if (!config) {
handleErrorResponse(
res,
200,
`Bucket name - ${file.bucket} not in config`,
);
return;
}
const gcsFile = storage.bucket(file.bucket).file(file.name);
// File.exists() returns a FileExistsResponse, which is a list with a
// single value.
if (!(await gcsFile.exists())[0]) {
// Warn but return successful to client.
logger.warn(
`Ignoring no longer existing file: gs://${file.bucket}/${file.name}`,
);
res.json({status: 'deleted'});
return;
}
const clamdVersion = await getClamVersion();
logger.info(
`Scan request for gs://${file.bucket}/${file.name}, (${fileSize} bytes) scanning with clam ${clamdVersion}`,
);
const startTime = Date.now();
const readStream = await gcsFile.createReadStream();
let result;
try {
result = await scanner.scanStream(readStream, CLAMD_TIMEOUT);
} finally {
// Ensure stream is destroyed in all situations to prevent any
// resource leaks.
readStream.destroy();
}
const scanDuration = Date.now() - startTime;
if (clamd.isCleanReply(result)) {
logger.info(
`Scan status for gs://${file.bucket}/${file.name}: CLEAN (${fileSize} bytes in ${scanDuration} ms)`,
);
metrics.writeScanClean(
config.unscanned,
config.clean,
fileSize,
scanDuration,
clamdVersion,
);
// Move document to the bucket that holds clean documents. This can
// fail due to permissions or if the file has been deleted.
await moveProcessedFile(file.name, true, config);
// Respond to API client.
res.json({status: 'clean', clam_version: clamdVersion});
} else {
logger.warn(
`Scan status for gs://${file.bucket}/${file.name}: INFECTED ${result} (${fileSize} bytes in ${scanDuration} ms)`,
);
metrics.writeScanInfected(
config.unscanned,
config.quarantined,
fileSize,
scanDuration,
clamdVersion,
);
// Move document to the bucket that holds infected documents. This can
// fail due to permissions or if the file has been deleted.
await moveProcessedFile(file.name, false, config);
// Respond to API client.
res.json({
message: result,
status: 'infected',
result: result,
clam_version: clamdVersion,
});
}
} catch (e) {
logger.error(
{err: e},
`Exception when processing gs://${file.bucket}/${file.name}: ${e}`,
);
// A 500 will cause Pubsub/EventArc to retry the event.
let statusCode = 500;
const errcode = /** @type {import('@google-cloud/storage').ApiError} */ (e)
.code;
if (errcode && [403, 404].includes(errcode)) {
// Permission denied/file not found can be raised by the stream reading
// and by the object move. They cannot be retried, so respond
// with success, but log the error.
statusCode = 200;
}
handleErrorResponse(
res,
statusCode,
`gs://${file.bucket}/${file.name}: ${e}`,
file.bucket,
);
}
}
/**
* Triggers a update check on the CVD Mirror GCS bucket.
*
* @param {!Request} req The request payload
* @param {!Response} res The HTTP response object
*/
async function handleCvdUpdate(req, res) {
try {
logger.info('Starting CVD Mirror update');
const result = await execFile('./updateCvdMirror.sh', [
BUCKET_CONFIG.ClamCvdMirrorBucket,
]);
logger.info('CVD Mirror update check complete. output:\n' + result.stdout);
// look for updated versions in output by looking for
// "updated (version: " from freshclam output.
const newVersions = result.stdout
.split('\n')
// Look for lines beginning with Downloaded
.filter((line) => line.indexOf('Downloaded') >= 0);
for (const version of newVersions) {
logger.info(`CVD Mirror updated: ${version}`);
}
res.json({
status: 'CvdUpdateComplete',
updated: newVersions.length > 0,
});
metrics.writeCvdMirrorUpdated(true, newVersions.length > 0);
} catch (err) {
const e = /** @type {any} */ (err);
logger.error(
{err: e},
`Failure when running updateCvdMirror: ${e}\nstdout: ${e.stdout}\nstderr: \n${e.stderr}`,
);
metrics.writeCvdMirrorUpdated(false, false);
res.status(500).json({message: e.message, status: 'CvdUpdateError'});
}
}
/**
* Trivial handler for get requests which returns the clam version.
*
* Use:
* curl -D - -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
CLOUD_RUN_APP_URL
* @param {!Request} req
* @param {!Response} res
*/
app.get('/', async (req, res) => {
res
.status(200)
.type('text/plain')
.send(
`${pkgJson.name} version ${pkgJson.version}
Using Clam AV version: ${await getClamVersion()}
${pkgJson.description}
`,
);
});
/**
* Respond with an error and log the message
*
* Note: any non-successful status codes will cause the caller (PubSub/Eventarc)
* to retry sending the event, so use 200 for non-retryable errors.
*
* @param {Response} res response object
* @param {number} statusCode
* @param {string} errorMessage
* @param {string?=} unscannedBucket
*/
function handleErrorResponse(
res,
statusCode,
errorMessage,
unscannedBucket = null,
) {
logger.error(`Error processing request: ${errorMessage}`);
res.status(statusCode).json({message: errorMessage, status: 'error'});
metrics.writeScanFailed(unscannedBucket);
}
/**
* Wrapper to get a clean string with the version of CLAM.
* @return {Promise<string>}
*/
async function getClamVersion() {
return (await clamd.version(CLAMD_HOST, CLAMD_PORT)).replace('\x00', '');
}
/**
* Move the file to the appropriate bucket.
* @async
* @param {string} filename
* @param {boolean} isClean
* @param {!import('./config.js').BucketDefs} config
*/
async function moveProcessedFile(filename, isClean, config) {
const srcfile = storage.bucket(config.unscanned).file(filename);
const destinationBucketName = isClean
? `gs://${config.clean}`
: `gs://${config.quarantined}`;
const destinationBucket = storage.bucket(destinationBucketName);
await srcfile.move(destinationBucket);
}
/**
* Wait up to 5 mins for ClamD to respond
*/
async function waitForClamD() {
const timeoutMins = 10;
const endTime = Date.now() + timeoutMins * 60 * 1000;
logger.info('Waiting for Clamd');
while (Date.now() < endTime) {
try {
const version = await getClamVersion();
logger.info(`Clamd started with version ${version}`);
return;
} catch (e) {
logger.warn(`Waiting for clamd to start: ${e}`);
}
await setTimeout(10000);
}
logger.fatal(`Clamd not started after ${timeoutMins} mins`);
process.exit(1);
}
/**
* Perform async setup and start the app.
*
* @async
*/
async function run() {
let projectId = process.env.PROJECT_ID;
if (!projectId) {
// Metrics needs project ID, so get it from GoogleAuth
projectId = await googleAuth.getProjectId();
}
await metrics.init(projectId);
let configFile;
if (process.argv.length >= 3) {
configFile = process.argv[2];
} else {
configFile = './config.json';
}
const config = await readAndVerifyConfig(configFile);
Object.assign(BUCKET_CONFIG, config);
await waitForClamD();
app.listen(PORT, () => {
logger.info(
`${pkgJson.name} version ${pkgJson.version} started on port ${PORT}`,
);
});
}
// Start the service, exiting on error.
run().catch((e) => {
logger.fatal(e);
logger.fatal('Exiting');
process.exit(1);
});