forked from kylefarris/clamscan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·2375 lines (2130 loc) · 110 KB
/
index.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
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
/* eslint-disable no-control-regex */
/* eslint-disable no-async-promise-executor */
/*!
* Node - Clam
* Copyright(c) 2013-2024 Kyle Farris <kylefarris@gmail.com>
* MIT Licensed
*/
// Module dependencies.
const os = require('os');
const net = require('net');
const fs = require('fs');
const nodePath = require('path'); // renamed to prevent conflicts in `scanDir`
const tls = require('tls');
const { promisify } = require('util');
const { execFile } = require('child_process');
const { PassThrough, Transform, Readable } = require('stream');
const { Socket } = require('dgram');
const fsPromises = require('fs').promises;
const NodeClamError = require('./lib/NodeClamError');
const NodeClamTransform = require('./lib/NodeClamTransform');
const getFiles = require('./lib/getFiles');
// Re-named `fs` promise methods to prevent conflicts while keeping short names
const fsAccess = fsPromises.access;
const fsReadfile = fsPromises.readFile;
const fsReaddir = fsPromises.readdir;
const fsStat = fsPromises.stat;
// Convert some stuff to promises
const cpExecFile = promisify(execFile);
/**
* NodeClam class definition.
*
* @class
* @public
* @typicalname NodeClam
*/
class NodeClam {
/**
* This sets up all the defaults of the instance but does not
* necessarily return an initialized instance. Use `.init` for that.
*/
constructor() {
this.initialized = false;
this.debugLabel = 'node-clam';
this.defaultScanner = 'clamdscan';
// Configuration Settings
this.defaults = Object.freeze({
removeInfected: false,
quarantineInfected: false,
scanLog: null,
debugMode: false,
fileList: null,
scanRecursively: true,
clamscan: {
path: '/usr/bin/clamscan',
scanArchives: true,
db: null,
active: true,
},
clamdscan: {
socket: false,
host: false,
port: false,
timeout: 60000, // 60 seconds
localFallback: true,
path: '/usr/bin/clamdscan',
configFile: null,
multiscan: true,
reloadDb: false,
active: true,
bypassTest: false,
tls: false,
},
preference: this.defaultScanner,
});
this.settings = { ...this.defaults };
}
/**
* Initialization method.
*
* @public
* @param {object} [options] - User options for the Clamscan module
* @param {boolean} [options.removeInfected=false] - If true, removes infected files when found
* @param {boolean|string} [options.quarantineInfected=false] - If not false, should be a string to a path to quarantine infected files
* @param {string} [options.scanLog=null] - Path to a writeable log file to write scan results into
* @param {boolean} [options.debugMode=false] - If true, *a lot* of info will be spewed to the logs
* @param {string} [options.fileList=null] - Path to file containing list of files to scan (for `scanFiles` method)
* @param {boolean} [options.scanRecursively=true] - If true, deep scan folders recursively (for `scanDir` method)
* @param {object} [options.clamscan] - Options specific to the clamscan binary
* @param {string} [options.clamscan.path='/usr/bin/clamscan'] - Path to clamscan binary on your server
* @param {string} [options.clamscan.db=null] - Path to a custom virus definition database
* @param {boolean} [options.clamscan.scanArchives=true] - If true, scan archives (ex. zip, rar, tar, dmg, iso, etc...)
* @param {boolean} [options.clamscan.active=true] - If true, this module will consider using the clamscan binary
* @param {object} [options.clamdscan] - Options specific to the clamdscan binary
* @param {string} [options.clamdscan.socket=false] - Path to socket file for connecting via TCP
* @param {string} [options.clamdscan.host=false] - IP of host to connec to TCP interface
* @param {string} [options.clamdscan.port=false] - Port of host to use when connecting via TCP interface
* @param {number} [options.clamdscan.timeout=60000] - Timeout for scanning files
* @param {boolean} [options.clamdscan.localFallback=false] - If false, do not fallback to a local binary-method of scanning
* @param {string} [options.clamdscan.path='/usr/bin/clamdscan'] - Path to the `clamdscan` binary on your server
* @param {string} [options.clamdscan.configFile=null] - Specify config file if it's in an usual place
* @param {boolean} [options.clamdscan.multiscan=true] - If true, scan using all available cores
* @param {boolean} [options.clamdscan.reloadDb=false] - If true, will re-load the DB on ever call (slow)
* @param {boolean} [options.clamdscan.active=true] - If true, this module will consider using the `clamdscan` binary
* @param {boolean} [options.clamdscan.bypassTest=false] - If true, check to see if socket is avaliable
* @param {boolean} [options.clamdscan.tls=false] - If true, connect to a TLS-Termination proxy in front of ClamAV
* @param {object} [options.preference='clamdscan'] - If preferred binary is found and active, it will be used by default
* @param {Function} [cb = null] - Callback method. Prototype: `(err, <instance of NodeClam>)`
* @returns {Promise<object>} An initated instance of NodeClam
* @example
* const NodeClam = require('clamscan');
* const ClamScan = new NodeClam().init({
* removeInfected: false,
* quarantineInfected: false,
* scanLog: null,
* debugMode: false,
* fileList: null,
* scanRecursively: true,
* clamscan: {
* path: '/usr/bin/clamscan',
* db: null,
* scanArchives: true,
* active: true
* },
* clamdscan: {
* socket: false,
* host: false,
* port: false,
* timeout: 60000,
* localFallback: false,
* path: '/usr/bin/clamdscan',
* configFile: null,
* multiscan: true,
* reloadDb: false,
* active: true,
* bypassTest: false,
* },
* preference: 'clamdscan'
});
*/
async init(options = {}, cb = null) {
let hasCb = false;
// Verify second param, if supplied, is a function
if (cb && typeof cb !== 'function') {
throw new NodeClamError(
'Invalid cb provided to init method. Second paramter, if provided, must be a function!'
);
} else if (cb && typeof cb === 'function') {
hasCb = true;
}
return new Promise(async (resolve, reject) => {
// No need to re-initialize
if (this.initialized === true) return hasCb ? cb(null, this) : resolve(this);
// Override defaults with user preferences
const settings = {};
if (Object.prototype.hasOwnProperty.call(options, 'clamscan') && Object.keys(options.clamscan).length > 0) {
settings.clamscan = { ...this.defaults.clamscan, ...options.clamscan };
delete options.clamscan;
}
if (
Object.prototype.hasOwnProperty.call(options, 'clamdscan') &&
Object.keys(options.clamdscan).length > 0
) {
settings.clamdscan = { ...this.defaults.clamdscan, ...options.clamdscan };
delete options.clamdscan;
}
this.settings = { ...this.defaults, ...settings, ...options };
if (this.settings && 'debugMode' in this.settings && this.settings.debugMode === true)
console.log(`${this.debugLabel}: DEBUG MODE ON`);
// Backwards compatibilty section
if ('quarantinePath' in this.settings && this.settings.quarantinePath) {
this.settings.quarantineInfected = this.settings.quarantinePath;
}
// Determine whether to use clamdscan or clamscan
this.scanner = this.defaultScanner;
// If scanner preference is not defined or is invalid, fallback to streaming scan or completely fail
if (
('preference' in this.settings && typeof this.settings.preference !== 'string') ||
!['clamscan', 'clamdscan'].includes(this.settings.preference)
) {
// If no valid scanner is found (but a socket/port/host is), disable the fallback to a local CLI scanning method
if (this.settings.clamdscan.socket || this.settings.clamdscan.port || this.settings.clamdscan.host) {
this.settings.clamdscan.localFallback = false;
} else {
const err = new NodeClamError(
'Invalid virus scanner preference defined and no valid socket/port/host option provided!'
);
return hasCb ? cb(err, null) : reject(err);
}
}
// Set 'clamscan' as the scanner preference if it's specified as such and activated
// OR if 'clamdscan is the preference but inactivated and clamscan is activated
if (
// If preference is 'clamscan' and clamscan is active
('preference' in this.settings &&
this.settings.preference === 'clamscan' &&
'clamscan' in this.settings &&
'active' in this.settings.clamscan &&
this.settings.clamscan.active === true) || // OR ... // If preference is 'clamdscan' and it's NOT active but 'clamscan' is...
(this.settings.preference === 'clamdscan' &&
'clamdscan' in this.settings &&
'active' in this.settings.clamdscan &&
this.settings.clamdscan.active !== true &&
'clamscan' in this.settings &&
'active' in this.settings.clamscan &&
this.settings.clamscan.active === true)
) {
// Set scanner to clamscan
this.scanner = 'clamscan';
}
// Check to make sure preferred scanner exists and actually is a clamscan binary
try {
// If scanner binary doesn't exist...
if (!(await this._isClamavBinary(this.scanner))) {
// Fall back to other option:
if (
this.scanner === 'clamdscan' &&
this.settings.clamscan.active === true &&
(await this._isClamavBinary('clamscan'))
) {
this.scanner = 'clamscan';
} else if (
this.scanner === 'clamscan' &&
this.settings.clamdscan.active === true &&
(await this._isClamavBinary('clamdscan'))
) {
this.scanner = 'clamdscan';
} else {
// If preferred scanner is not a valid binary but there is a socket/port/host option, disable
// failover to local CLI implementation
if (
!this.settings.clamdscan.socket &&
!this.settings.clamdscan.port &&
!this.settings.clamdscan.host
) {
const err = new NodeClamError(
'No valid & active virus scanning binaries are active and available and no socket/port/host option provided!'
);
return hasCb ? cb(err, null) : reject(err);
}
this.settings.clamdscan.localFallback = false;
}
}
} catch (err) {
return hasCb ? cb(err, null) : reject(err);
}
// Make sure quarantineInfected path exists at specified location
if (
!this.settings.clamdscan.socket &&
!this.settings.clamdscan.port &&
!this.settings.clamdscan.host &&
((this.settings.clamdscan.active === true && this.settings.clamdscan.localFallback === true) ||
this.settings.clamscan.active === true) &&
this.settings.quarantineInfected
) {
try {
await fsAccess(this.settings.quarantineInfected, fs.constants.R_OK);
} catch (e) {
if (this.settings.debugMode) console.log(`${this.debugLabel} error:`, e);
const err = new NodeClamError(
{ err: e },
`Quarantine infected path (${this.settings.quarantineInfected}) is invalid.`
);
return hasCb ? cb(err, null) : reject(err);
}
}
// If using clamscan, make sure definition db exists at specified location
if (
!this.settings.clamdscan.socket &&
!this.settings.clamdscan.port &&
!this.settings.clamdscan.host &&
this.scanner === 'clamscan' &&
this.settings.clamscan.db
) {
try {
await fsAccess(this.settings.clamscan.db, fs.constants.R_OK);
} catch (err) {
if (this.settings.debugMode) console.log(`${this.debugLabel} error:`, err);
// throw new Error(`Definitions DB path (${this.settings.clamscan.db}) is invalid.`);
this.settings.clamscan.db = null;
}
}
// Make sure scanLog exists at specified location
if (
((!this.settings.clamdscan.socket && !this.settings.clamdscan.port && !this.settings.clamdscan.host) ||
((this.settings.clamdscan.socket || this.settings.clamdscan.port || this.settings.clamdscan.host) &&
this.settings.clamdscan.localFallback === true &&
this.settings.clamdscan.active === true) ||
(this.settings.clamdscan.active === false && this.settings.clamscan.active === true) ||
this.preference) &&
this.settings.scanLog
) {
try {
await fsAccess(this.settings.scanLog, fs.constants.R_OK);
} catch (err) {
// console.log("DID NOT Find scan log!");
// foundScanLog = false;
if (this.settings.debugMode) console.log(`${this.debugLabel} error:`, err);
// throw new Error(`Scan Log path (${this.settings.scanLog}) is invalid.` + err);
this.settings.scanLog = null;
}
}
// Check the availability of the clamd service if socket or host/port are provided
if (
this.scanner === 'clamdscan' &&
this.settings.clamdscan.bypassTest === false &&
(this.settings.clamdscan.socket || this.settings.clamdscan.port || this.settings.clamdscan.host)
) {
if (this.settings.debugMode)
console.log(`${this.debugLabel}: Initially testing socket/tcp connection to clamscan server.`);
try {
const client = await this.ping();
client.end();
if (this.settings.debugMode)
console.log(`${this.debugLabel}: Established connection to clamscan server!`);
} catch (err) {
return hasCb ? cb(err, null) : reject(err);
}
}
// if (foundScanLog === false) console.log("No Scan Log: ", this.settings);
// Build clam flags
this.clamFlags = this._buildClamFlags(this.scanner, this.settings);
// if (foundScanLog === false) console.log("No Scan Log: ", this.settings);
// This ClamScan instance is now initialized
this.initialized = true;
// Return instance based on type of expected response (callback vs promise)
return hasCb ? cb(null, this) : resolve(this);
});
}
/**
* Allows one to create a new instances of clamscan with new options.
*
* @public
* @param {object} [options = {}] - Same options as the `init` method
* @param {Function} [cb = null] - What to do after reset (repsponds with reset instance of NodeClam)
* @returns {Promise<object>} A reset instance of NodeClam
*/
reset(options = {}, cb = null) {
let hasCb = false;
// Verify second param, if supplied, is a function
if (cb && typeof cb !== 'function') {
throw new NodeClamError(
'Invalid cb provided to `reset`. Second paramter, if provided, must be a function!'
);
} else if (cb && typeof cb === 'function') {
hasCb = true;
}
this.initialized = false;
this.settings = { ...this.defaults };
return new Promise(async (resolve, reject) => {
try {
await this.init(options);
return hasCb ? cb(null, this) : resolve(this);
} catch (err) {
return hasCb ? cb(err, null) : reject(err);
}
});
}
// *****************************************************************************
// Builds out the args to pass to execFile
// -----
// @param String|Array item The file(s) / directory(ies) to append to the args
// @api Private
// *****************************************************************************
/**
* Builds out the args to pass to `execFile`.
*
* @private
* @param {string|Array} item - The file(s) / directory(ies) to append to the args
* @returns {string|Array} The string or array of arguments
* @example
* this._buildClamArgs('--version');
*/
_buildClamArgs(item) {
let args = this.clamFlags.slice();
if (typeof item === 'string') args.push(item);
if (Array.isArray(item)) args = args.concat(item);
return args;
}
/**
* Builds out the flags based on the configuration the user provided.
*
* @private
* @param {string} scanner - The scanner to use (clamscan or clamdscan)
* @param {object} settings - The settings used to build the flags
* @returns {string} The concatenated clamav flags
* @example
* // Build clam flags
* this.clamFlags = this._buildClamFlags(this.scanner, this.settings);
*/
_buildClamFlags(scanner, settings) {
const flagsArray = ['--no-summary'];
// Flags specific to clamscan
if (scanner === 'clamscan') {
flagsArray.push('--stdout');
// Remove infected files
if (settings.removeInfected === true) {
flagsArray.push('--remove=yes');
} else {
flagsArray.push('--remove=no');
}
// Database file
if (
'clamscan' in settings &&
typeof settings.clamscan === 'object' &&
'db' in settings.clamscan &&
settings.clamscan.db &&
typeof settings.clamscan.db === 'string'
)
flagsArray.push(`--database=${settings.clamscan.db}`);
// Scan archives
if (settings.clamscan.scanArchives === true) {
flagsArray.push('--scan-archive=yes');
} else {
flagsArray.push('--scan-archive=no');
}
// Recursive scanning (flag is specific, feature is not)
if (settings.scanRecursively === true) {
flagsArray.push('-r');
} else {
flagsArray.push('--recursive=no');
}
}
// Flags specific to clamdscan
else if (scanner === 'clamdscan') {
flagsArray.push('--fdpass');
// Remove infected files
if (settings.removeInfected === true) flagsArray.push('--remove');
// Specify a config file
if (
'clamdscan' in settings &&
typeof settings.clamdscan === 'object' &&
'configFile' in settings.clamdscan &&
settings.clamdscan.configFile &&
typeof settings.clamdscan.configFile === 'string'
)
flagsArray.push(`--config-file=${settings.clamdscan.configFile}`);
// Turn on multi-threaded scanning
if (settings.clamdscan.multiscan === true) flagsArray.push('--multiscan');
// Reload the virus DB
if (settings.clamdscan.reloadDb === true) flagsArray.push('--reload');
}
// ***************
// Common flags
// ***************
// Remove infected files
if (settings.removeInfected !== true) {
if (
'quarantineInfected' in settings &&
settings.quarantineInfected &&
typeof settings.quarantineInfected === 'string'
) {
flagsArray.push(`--move=${settings.quarantineInfected}`);
}
}
// Write info to a log
if ('scanLog' in settings && settings.scanLog && typeof settings.scanLog === 'string')
flagsArray.push(`--log=${settings.scanLog}`);
// Read list of files to scan from a file
if ('fileList' in settings && settings.fileList && typeof settings.fileList === 'string')
flagsArray.push(`--file-list=${settings.fileList}`);
// Build the String
return flagsArray;
}
/**
* Create socket connection to a remote(or local) clamav daemon.
*
* @private
* @param {string} [label] - A label you can provide for debugging
* @returns {Promise<Socket>} A Socket/TCP connection to ClamAV
* @example
* const client = this._initSocket('whatever');
*/
_initSocket(label = '') {
return new Promise((resolve, reject) => {
if (this.settings.debugMode)
console.log(`${this.debugLabel}: Attempting to establish socket/TCP connection for "${label}"`);
// Create a new Socket connection to Unix socket or remote server (in that order)
let client;
// Setup socket connection timeout (default: 20 seconds).
const timeout = this.settings.clamdscan.timeout ? this.settings.clamdscan.timeout : 20000;
// The fastest option is a local Unix socket
if (this.settings.clamdscan.socket)
client = net.createConnection({ path: this.settings.clamdscan.socket, timeout });
// If a port is specified, we're going to be connecting via TCP
else if (this.settings.clamdscan.port) {
// If a host is specified (usually for a remote host)
if (this.settings.clamdscan.host) {
if (this.settings.clamdscan.tls) {
client = tls.connect({
host: this.settings.clamdscan.host,
port: this.settings.clamdscan.port,
// Activate SNI
// servername: this.settings.clamdscan.host,
timeout,
});
} else {
client = net.createConnection({
host: this.settings.clamdscan.host,
port: this.settings.clamdscan.port,
timeout,
});
}
}
// Host can be ignored since the default is `localhost`
else if (this.settings.tls) {
client = tls.connect({ port: this.settings.clamdscan.port, timeout });
} else {
client = net.createConnection({ port: this.settings.clamdscan.port, timeout });
}
}
// No valid option to connection can be determined
else
throw new NodeClamError(
'Unable not establish connection to clamd service: No socket or host/port combo provided!'
);
// Set the socket timeout if specified
if (this.settings.clamdscan.timeout) client.setTimeout(this.settings.clamdscan.timeout);
// Setup socket client listeners
client
.on('connect', () => {
// Some basic debugging stuff...
// Determine information about what server the client is connected to
if (client.remotePort && client.remotePort.toString() === this.settings.clamdscan.port.toString()) {
if (this.settings.debugMode)
console.log(
`${this.debugLabel}: using remote server: ${client.remoteAddress}:${client.remotePort}`
);
} else if (this.settings.clamdscan.socket) {
if (this.settings.debugMode)
console.log(
`${this.debugLabel}: using local unix domain socket: ${this.settings.clamdscan.socket}`
);
} else if (this.settings.debugMode) {
const { port, address } = client.address();
console.log(`${this.debugLabel}: meta port value: ${port} vs ${client.remotePort}`);
console.log(`${this.debugLabel}: meta address value: ${address} vs ${client.remoteAddress}`);
console.log(`${this.debugLabel}: something is not working...`);
}
return resolve(client);
})
.on('timeout', () => {
if (this.settings.debugMode) console.log(`${this.debugLabel}: Socket/Host connection timed out.`);
reject(new Error('Connection to host has timed out.'));
client.end();
})
.on('close', () => {
if (this.settings.debugMode) console.log(`${this.debugLabel}: Socket/Host connection closed.`);
})
.on('error', (e) => {
if (this.settings.debugMode) console.error(`${this.debugLabel}: Socket/Host connection failed:`, e);
reject(e);
});
});
}
/**
* Checks to see if a particular binary is a clamav binary. The path for the
* binary must be specified in the NodeClam config at `init`. If you have a
* config file in an unusual place, make sure you specify that in `init` configs
* as well.
*
* @private
* @param {string} scanner - The ClamAV scanner (clamscan or clamdscan) to verify
* @returns {Promise<boolean>} True if binary is a ClamAV binary, false if not.
* @example
* const clamscanIsGood = this._isClamavBinary('clamscan');
*/
async _isClamavBinary(scanner) {
const { path = null, configFile = null } = this.settings[scanner];
if (!path) {
if (this.settings.debugMode) console.log(`${this.debugLabel}: Could not determine path for clamav binary.`);
return false;
}
const versionCmds = {
clamdscan: ['--version'],
clamscan: ['--version'],
};
if (configFile) {
versionCmds[scanner].push(`--config-file=${configFile}`);
}
try {
await fsAccess(path, fs.constants.R_OK);
const { stdout } = await cpExecFile(path, versionCmds[scanner]);
if (stdout.toString().match(/ClamAV/) === null) {
if (this.settings.debugMode) console.log(`${this.debugLabel}: Could not verify the ${scanner} binary.`);
return false;
}
return true;
} catch (err) {
if (this.settings.debugMode)
console.log(`${this.debugLabel}: Could not verify the ${scanner} binary.`, err);
return false;
}
}
/**
* Really basic method to check if the configured `host` is actually the localhost
* machine. It's not flawless but a decently acurate check for our purposes.
*
* @private
* @returns {boolean} Returns `true` if the clamdscan host is local, `false` if not.
* @example
* const isLocal = this._isLocalHost();
*/
_isLocalHost() {
return ['127.0.0.1', 'localhost', os.hostname()].includes(this.settings.clamdscan.host);
}
/**
* Test to see if ab object is a readable stream.
*
* @private
* @param {object} obj - Object to test "streaminess" of
* @returns {boolean} Returns `true` if provided object is a stream; `false` if not.
* @example
* // Yay!
* const isStream = this._isReadableStream(someStream);
*
* // Nay!
* const isString = this._isReadableString('foobar');
*/
_isReadableStream(obj) {
if (!obj || typeof obj !== 'object') return false;
return typeof obj.pipe === 'function' && typeof obj._readableState === 'object';
}
/**
* Alias `ping()` for backwards-compatibility with older package versions.
*
* @private
* @alias ping
* @param {Function} [cb] - Callback function
* @returns {Promise<object>} A copy of the Socket/TCP client
*/
_ping(cb = null) {
return this.ping(cb);
}
/**
* This is what actually processes the response from clamav.
*
* @private
* @param {string} result - The ClamAV result to process and interpret
* @param {string} [file=null] - The name of the file/path that was scanned
* @returns {object} Contains `isInfected` boolean and `viruses` array
* @example
* const args = this._buildClamArgs('/some/file/here');
* execFile(this.settings[this.scanner].path, args, (err, stdout, stderr) => {
* const { isInfected, viruses } = this._processResult(stdout, file);
* console.log('Infected? ', isInfected);
* });
*/
_processResult(result, file = null) {
let timeout = false;
// The result value must be a string otherwise we can't parse it
if (typeof result !== 'string') {
if (this.settings.debugMode)
console.log(`${this.debugLabel}: Invalid stdout from scanner (not a string): `, result);
throw new Error('Invalid result to process (not a string)');
}
// Clean up the result string so that its predictably parseable
result = result.trim();
// If the result string looks like 'Anything Here: OK\n', the scanned file is not infected
// eslint-disable-next-line no-control-regex
if (/:\s+OK(\u0000|[\r\n])?$/.test(result)) {
if (this.settings.debugMode) console.log(`${this.debugLabel}: File is OK!`);
return { isInfected: false, viruses: [], file, resultString: result, timeout };
}
// If the result string looks like 'Anything Here: SOME VIRUS FOUND\n', the file is infected
// eslint-disable-next-line no-control-regex
if (/:\s+(.+)FOUND(\u0000|[\r\n])?/gm.test(result)) {
if (this.settings.debugMode) {
if (this.settings.debugMode) console.log(`${this.debugLabel}: Scan Response: `, result);
if (this.settings.debugMode) console.log(`${this.debugLabel}: File is INFECTED!`);
}
// Parse out the name of the virus(es) found...
const viruses = Array.from(
new Set(
result
// eslint-disable-next-line no-control-regex
.split(/(\u0000|[\r\n])/)
.map((v) => (/:\s+(.+)FOUND$/gm.test(v) ? v.replace(/(.+:\s+)(.+)FOUND/gm, '$2').trim() : null))
.filter((v) => !!v)
)
);
return { isInfected: true, viruses, file, resultString: result, timeout };
}
// If the result of the scan ends with "ERROR", there was an error (file permissions maybe)
if (/^(.+)ERROR(\u0000|[\r\n])?/gm.test(result)) {
const error = result.replace(/^(.+)ERROR/gm, '$1').trim();
if (this.settings.debugMode) {
if (this.settings.debugMode) console.log(`${this.debugLabel}: Error Response: `, error);
if (this.settings.debugMode) console.log(`${this.debugLabel}: File may be INFECTED!`);
}
return new NodeClamError({ error }, `An error occurred while scanning the piped-through stream: ${error}`);
}
// This will occur in the event of a timeout (rare)
if (result === 'COMMAND READ TIMED OUT') {
timeout = true;
if (this.settings.debugMode) {
if (this.settings.debugMode)
console.log(`${this.debugLabel}: Scanning file has timed out. Message: `, result);
if (this.settings.debugMode) console.log(`${this.debugLabel}: File may be INFECTED!`);
}
return { isInfected: null, viruses: [], file, resultString: result, timeout };
}
if (this.settings.debugMode) {
if (this.settings.debugMode) console.log(`${this.debugLabel}: Error Response: `, result);
if (this.settings.debugMode) console.log(`${this.debugLabel}: File may be INFECTED!`);
}
return { isInfected: null, viruses: [], file, resultString: result, timeout };
}
/**
* Establish the clamav version of a local or remote clamav daemon.
*
* @public
* @param {Function} [cb] - What to do when version is established
* @returns {Promise<string>} - The version of ClamAV that is being interfaced with
* @example
* // Callback example
* clamscan.getVersion((err, version) => {
* if (err) return console.error(err);
* console.log(`ClamAV Version: ${version}`);
* });
*
* // Promise example
* const clamscan = new NodeClam().init();
* const version = await clamscan.getVersion();
* console.log(`ClamAV Version: ${version}`);
*/
getVersion(cb) {
const self = this;
let hasCb = false;
// Verify second param, if supplied, is a function
if (cb && typeof cb !== 'function')
throw new NodeClamError('Invalid cb provided to scanStream. Second paramter must be a function!');
// Making things simpler
if (cb && typeof cb === 'function') hasCb = true;
// eslint-disable-next-line consistent-return
return new Promise(async (resolve, reject) => {
// Function for falling back to running a scan locally via a child process
const localFallback = async () => {
const args = self._buildClamArgs('--version');
if (self.settings.debugMode)
console.log(
`${this.debugLabel}: Configured clam command: ${self.settings[self.scanner].path}`,
args.join(' ')
);
// Execute the clam binary with the proper flags
try {
const { stdout, stderr } = await cpExecFile(`${self.settings[self.scanner].path}`, args);
if (stderr) {
const err = new NodeClamError(
{ stderr, file: null },
'ClamAV responded with an unexpected response when requesting version.'
);
if (self.settings.debugMode) console.log(`${this.debugLabel}: `, err);
return hasCb ? cb(err, null, null) : reject(err);
}
return hasCb ? cb(null, stdout) : resolve(stdout);
} catch (e) {
if (Object.prototype.hasOwnProperty.call(e, 'code') && e.code === 1) {
return hasCb ? cb(null, null) : resolve(null, null);
}
const err = new NodeClamError({ err: e }, 'There was an error requestion ClamAV version.');
if (self.settings.debugMode) console.log(`${this.debugLabel}: `, err);
return hasCb ? cb(err, null) : reject(err);
}
};
// If user wants to connect via socket or TCP...
if (
this.scanner === 'clamdscan' &&
(this.settings.clamdscan.socket || this.settings.clamdscan.port || this.settings.clamdscan.host)
) {
const chunks = [];
let client;
try {
client = await this._initSocket('getVersion');
client.write('nVERSION\n');
// ClamAV is sending stuff to us
client.on('data', (chunk) => chunks.push(chunk));
client.on('end', () => {
const response = Buffer.concat(chunks);
client.end();
return hasCb ? cb(null, response.toString()) : resolve(response.toString());
});
} catch (err) {
if (client && 'readyState' in client && client.readyState) client.end();
if (this.settings.clamdscan.localFallback === true) {
return localFallback();
}
return hasCb ? cb(err, null) : reject(err);
}
} else {
return localFallback();
}
});
}
/**
* This method allows you to scan a single file. It supports a callback and Promise API.
* If no callback is supplied, a Promise will be returned. This method will likely
* be the most common use-case for this module.
*
* @public
* @param {string} file - Path to the file to check
* @param {Function} [cb = null] - What to do after the scan
* @returns {Promise<object>} Object like: `{ file: String, isInfected: Boolean, viruses: Array }`
* @example
* // Callback Example
* clamscan.isInfected('/a/picture/for_example.jpg', (err, file, isInfected, viruses) => {
* if (err) return console.error(err);
*
* if (isInfected) {
* console.log(`${file} is infected with ${viruses.join(', ')}.`);
* }
* });
*
* // Promise Example
* clamscan.isInfected('/a/picture/for_example.jpg').then(result => {
* const {file, isInfected, viruses} = result;
* if (isInfected) console.log(`${file} is infected with ${viruses.join(', ')}.`);
* }).then(err => {
* console.error(err);
* });
*
* // Async/Await Example
* const {file, isInfected, viruses} = await clamscan.isInfected('/a/picture/for_example.jpg');
*/
isInfected(file = '', cb = null) {
const self = this;
let hasCb = false;
// Verify second param, if supplied, is a function
if (cb && typeof cb !== 'function') {
throw new NodeClamError(
'Invalid cb provided to isInfected. Second paramter, if provided, must be a function!'
);
} else if (cb && typeof cb === 'function') {
hasCb = true;
}
// At this point for the hybrid Promise/CB API to work, everything needs to be wrapped
// in a Promise that will be returned
// eslint-disable-next-line consistent-return
return new Promise(async (resolve, reject) => {
// Verify string is passed to the file parameter
if (typeof file !== 'string' || (typeof file === 'string' && file.trim() === '')) {
const err = new NodeClamError({ file }, 'Invalid or empty file name provided.');
return hasCb ? cb(err, file, null, []) : reject(err);
}
// Clean file name
file = file.trim();
// This is the function used for scanning viruses using the clamd command directly
const localScan = () => {
if (self.settings.debugMode) console.log(`${this.debugLabel}: [Local Scan] Scanning ${file}`);
// Build the actual command to run
const args = self._buildClamArgs(file);
if (self.settings.debugMode)
console.log(
`${this.debugLabel}: Configured clam command: ${self.settings[self.scanner].path}`,
args.join(' ')
);
// Execute the clam binary with the proper flags
// NOTE: The async/await version of this will not allow us to capture the virus(es) name(s).
execFile(self.settings[self.scanner].path, args, (err, stdout, stderr) => {
const { isInfected, viruses } = self._processResult(stdout, file);
// It may be a real error or a virus may have been found.
if (err) {
// Code 1 is when a virus is found... It's not really an "error", per se...
if (Object.prototype.hasOwnProperty.call(err, 'code') && err.code === 1) {
return hasCb ? cb(null, file, true, viruses) : resolve({ file, isInfected, viruses });
}
const error = new NodeClamError(
{ file, err, isInfected: null },
`There was an error scanning the file (ClamAV Error Code: ${err.code})`
);
if (self.settings.debugMode) console.log(`${this.debugLabel}`, error);
return hasCb ? cb(error, file, null, []) : reject(error);
}
// Not sure in what scenario a `stderr` would show up, but, it's worth handling here
if (stderr) {
const error = new NodeClamError(
{ stderr, file },
'The file was scanned but ClamAV responded with an unexpected response.'
);
if (self.settings.debugMode) console.log(`${this.debugLabel}: `, error);
return hasCb ? cb(error, file, null, viruses) : resolve({ file, isInfected, viruses });
}
// No viruses were found!
try {
return hasCb ? cb(null, file, isInfected, viruses) : resolve({ file, isInfected, viruses });
} catch (e) {
const error = new NodeClamError(
{ file, err: e, isInfected: null },
'There was an error processing the results from ClamAV'
);
return hasCb ? cb(error, file, null, []) : reject(error);
}
});
};
// See if we can find/read the file
// -----
// NOTE: Is it even valid to do this since, in theory, the
// file's existance or permission could change between this check
// and the actual scan (even if it's highly unlikely)?
//-----
try {
await fsAccess(file, fs.constants.R_OK);
} catch (e) {
const err = new NodeClamError({ err: e, file }, 'Could not find file to scan!');
return hasCb ? cb(err, file, true) : reject(err);
}
// Make sure the "file" being scanned is actually a file and not a directory (or something else)
try {