-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcallback.rs
More file actions
1711 lines (1572 loc) · 59.9 KB
/
Copy pathcallback.rs
File metadata and controls
1711 lines (1572 loc) · 59.9 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
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
// Copyright (C) 2020-2023 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
use crate::{engine::ScanEvent, fmap::Fmap, EngineError};
use clamav_sys::cl_error_t;
use std::{
ffi::CStr,
os::raw::{c_char, c_void},
panic::{self, AssertUnwindSafe},
sync::Arc,
};
/// A wrapper structure around the context passed to callbacks that execute with scans
pub(crate) struct ScanCbContext {
pub(crate) sender: tokio::sync::mpsc::Sender<ScanEvent>,
pub(crate) scan_context: Option<ScanContext>,
/// Additional user-defined logic for various callback types
pub(crate) pre_scan_logic: Option<Arc<dyn std::any::Any + Send + Sync>>,
pub(crate) post_scan_logic: Option<Arc<dyn std::any::Any + Send + Sync>>,
pub(crate) match_logic: Option<Arc<dyn std::any::Any + Send + Sync>>,
pub(crate) file_type_logic: Option<Arc<dyn std::any::Any + Send + Sync>>,
}
/// The scan callback hook points supported by [`crate::engine::Engine`].
pub enum EngineCallback {
/// Invoked before a scan layer is scanned.
PreScan,
/// Invoked after a scan layer has been scanned.
PostScan,
/// Invoked when libclamav reports a match for a scan layer.
Match,
/// Invoked when libclamav identifies the type of a scan layer.
FileType,
}
/// Opaque per-scan application context forwarded to scan callbacks.
///
/// The wrapped pointer is never dereferenced by this crate. Callers are
/// responsible for ensuring that any pointed-to data remains valid and is safe
/// to access from the blocking scan worker thread for the entire scan.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ScanContext(*mut c_void);
impl ScanContext {
/// Creates a new opaque scan context from a raw pointer.
pub fn from_ptr(ptr: *mut c_void) -> Self {
Self(ptr)
}
/// Returns the wrapped raw pointer.
pub fn as_ptr(self) -> *mut c_void {
self.0
}
}
// Safety: this type only carries an opaque pointer value. Callers are
// responsible for ensuring that the pointed-to data is valid to access across
// threads for the duration of the scan.
unsafe impl Send for ScanContext {}
unsafe impl Sync for ScanContext {}
/// Trait object type used for scan-layer callback closures.
///
/// Callback logic receives mutable access to a [`ScanLayer`] so it can inspect
/// the current layer and optionally cache its [`Fmap`]. The optional scan
/// context is an opaque per-scan pointer supplied by the caller of
/// [`crate::engine::Engine::scan`]; this crate stores and forwards the pointer
/// but never dereferences it.
pub type ScanLayerLogic =
dyn Fn(&mut ScanLayer, Option<ScanContext>) -> ScanLogicResult + Send + Sync;
/// Callback signature used for pre-scan callbacks.
pub type PreScanLogic = ScanLayerLogic;
/// Callback signature used for post-scan callbacks.
pub type PostScanLogic = ScanLayerLogic;
/// Callback signature used for file-type callbacks.
pub type FileTypeLogic = ScanLayerLogic;
/// Callback signature used for match callbacks.
pub type MatchLogic = ScanLayerLogic;
/// The decision returned by a scan callback.
///
/// These values are forwarded to libclamav and can alter the final scan
/// outcome, not just the control flow of the callback itself.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScanLogicResult {
/// Abort the scan immediately.
Abort,
/// Continue scanning without forcing a match or trusted result.
Success,
/// Accept or create a match and continue scanning.
Match,
/// Mark the layer as trusted, discard prior matches in the layer, and stop
/// scanning the layer. Parent layers will not be trusted and the scan will continue.
Trust,
}
fn scan_logic_result_to_cl(result: ScanLogicResult) -> cl_error_t {
match result {
ScanLogicResult::Abort => cl_error_t::CL_BREAK,
ScanLogicResult::Success => cl_error_t::CL_SUCCESS,
ScanLogicResult::Match => cl_error_t::CL_VIRUS,
ScanLogicResult::Trust => cl_error_t::CL_VERIFIED,
}
}
fn invoke_scan_logic(
logic: &ScanLayerLogic,
scan_layer: &mut ScanLayer,
scan_context: Option<ScanContext>,
callback_name: &'static str,
) -> Result<ScanLogicResult, cl_error_t> {
match panic::catch_unwind(AssertUnwindSafe(|| logic(scan_layer, scan_context))) {
Ok(decision) => Ok(decision),
Err(_) => {
log::error!("panic in {callback_name} scan callback; aborting scan");
Err(cl_error_t::CL_BREAK)
}
}
}
/// A completion progress report, with a final result
#[derive(Debug)]
pub enum Progress<T, E> {
/// An intermediate progress update.
Update {
/// How many elements have been handled
now_completed: usize,
/// How many elements are expected to be handled
total_items: usize,
},
/// The terminal result of the operation.
Complete(Result<T, E>),
}
/// Wrapper function for callbacks that accept a Progress message
///
/// This function has libclamav's `clcb_progress` function signature
pub(crate) unsafe extern "C" fn progress(
total_items: usize,
now_completed: usize,
context: *mut c_void,
) -> cl_error_t {
// All errors are handled silently as there is no other means to report errors
if let Some(sender) = context
.cast::<tokio::sync::mpsc::Sender<Progress<(), EngineError>>>()
.as_ref()
{
let _ = sender.blocking_send(Progress::Update {
total_items,
now_completed,
});
}
// ClamAV doesn't specify any action on this value, so it's hardcoded into
// the wrapper
cl_error_t::CL_SUCCESS
}
/// Metadata and content access for the current libclamav scan layer.
///
/// A `ScanLayer` is only valid while the callback is executing. If you need to
/// keep any data after the callback returns, copy it out during the callback.
pub struct ScanLayer {
layer: *mut clamav_sys::cl_scan_layer_t,
fmap: Option<Fmap>,
}
impl ScanLayer {
pub(crate) fn new(layer: *mut clamav_sys::cl_scan_layer_t) -> Self {
Self { layer, fmap: None }
}
/// Returns the libclamav object id for the current scan layer.
pub fn object_id(&self) -> Result<u64, EngineError> {
let mut object_id: u64 = 0;
let cl_result: cl_error_t = unsafe {
clamav_sys::cl_scan_layer_get_object_id(self.layer, &mut object_id as *mut u64)
};
if cl_result != cl_error_t::CL_SUCCESS {
Err(EngineError::Clam(crate::error::Error::from(cl_result)))
} else {
Ok(object_id)
}
}
/// Returns the libclamav type string for the current scan layer.
pub fn type_(&self) -> Result<String, EngineError> {
let mut type_: *const c_char = std::ptr::null();
let cl_result: cl_error_t = unsafe {
clamav_sys::cl_scan_layer_get_type(self.layer, &mut type_ as *mut *const c_char)
};
if cl_result != cl_error_t::CL_SUCCESS || type_.is_null() {
Err(EngineError::Clam(crate::error::Error::from(cl_result)))
} else {
let file_type = unsafe { CStr::from_ptr(type_).to_string_lossy().into_owned() };
Ok(file_type)
}
}
/// Returns the mapped file backing this scan layer.
///
/// The first call fetches and caches the layer fmap from libclamav.
pub fn fmap(&mut self) -> Result<&Fmap, EngineError> {
if self.fmap.is_none() {
let mut fmap_ptr: *mut clamav_sys::cl_fmap_t = std::ptr::null_mut();
let cl_result: cl_error_t = unsafe {
clamav_sys::cl_scan_layer_get_fmap(self.layer, &mut fmap_ptr as *mut *mut _)
};
if cl_result != cl_error_t::CL_SUCCESS || fmap_ptr.is_null() {
return Err(EngineError::Clam(crate::error::Error::from(cl_result)));
}
let fmap = unsafe { Fmap::from_raw_borrowed(fmap_ptr) };
self.fmap = Some(fmap);
}
// Safe to unwrap: we either had a cached fmap or just populated it above.
Ok(self.fmap.as_ref().unwrap())
}
/// Returns the object ids of all ancestor layers, nearest parent first.
pub fn ancestor_ids(&self) -> Result<Vec<u64>, EngineError> {
let mut ancestors = Vec::new();
let mut layer = self.layer;
loop {
let mut parent_layer: *mut clamav_sys::cl_scan_layer_t = std::ptr::null_mut();
let cl_result = unsafe {
clamav_sys::cl_scan_layer_get_parent_layer(
layer,
&mut parent_layer as *mut *mut clamav_sys::cl_scan_layer_t,
)
};
if cl_result != cl_error_t::CL_SUCCESS || parent_layer.is_null() {
break;
}
let parent = ScanLayer::new(parent_layer);
ancestors.push(parent.object_id()?);
layer = parent_layer;
}
Ok(ancestors)
}
/// Returns the file name associated with the layer, if one is available.
pub fn file_name(&mut self) -> Option<String> {
let fmap = self.fmap().ok()?;
fmap.name().ok().flatten()
}
/// Returns the byte length of the layer, or `0` if it cannot be retrieved.
pub fn file_size(&mut self) -> usize {
self.fmap().and_then(|fmap| fmap.size()).unwrap_or(0)
}
/// Returns the SHA-256 digest for the layer contents.
pub fn sha2_256(&mut self) -> Result<String, EngineError> {
let fmap = self.fmap()?;
fmap.sha2_256()
}
/// Returns a slice of the layer data.
///
/// Passing `len == 0` requests the remainder of the layer from `offset`.
/// The returned slice is borrowed from libclamav-managed memory and must
/// not outlive the callback.
pub fn data(&mut self, offset: usize, len: usize) -> Result<&[u8], EngineError> {
if self.fmap.is_none() {
let _ = self.fmap()?;
}
self.fmap
.as_ref()
.expect("fmap should be cached after retrieval")
.data(offset, len)
}
/// Returns the most recent match name attached to the layer, if any.
pub fn last_match(&self) -> Result<Option<String>, EngineError> {
let mut match_out: *const c_char = std::ptr::null();
let cl_result =
unsafe { clamav_sys::cl_scan_layer_get_last_alert(self.layer, &mut match_out) };
if cl_result != cl_error_t::CL_SUCCESS {
Err(EngineError::Clam(crate::error::Error::from(cl_result)))
} else if match_out.is_null() {
Ok(None)
} else {
Ok(Some(
unsafe { CStr::from_ptr(match_out) }
.to_string_lossy()
.into_owned(),
))
}
}
}
pub(crate) unsafe extern "C" fn engine_callback_match(
layer: *mut clamav_sys::cl_scan_layer_t,
context: *mut c_void,
) -> cl_error_t {
let mut decision = ScanLogicResult::Success;
if let Some(cxt) = context.cast::<ScanCbContext>().as_ref() {
let mut scan_layer = ScanLayer::new(layer);
if scan_layer.fmap().is_err() {
// Return CL_VIRUS to preserve the match, despite the error in this handler.
return cl_error_t::CL_VIRUS;
}
let object_id = match scan_layer.object_id() {
Ok(id) => id,
// Return CL_VIRUS to preserve the match, despite the error in this handler.
Err(_) => return cl_error_t::CL_VIRUS,
};
let file_type = match scan_layer.type_() {
Ok(ft) => ft,
// Return CL_VIRUS to preserve the match, despite the error in this handler.
Err(_) => return cl_error_t::CL_VIRUS,
};
let ancestor_ids = match scan_layer.ancestor_ids() {
Ok(ids) => ids,
// Return CL_VIRUS to preserve the match, despite the error in this handler.
Err(_) => return cl_error_t::CL_VIRUS,
};
let file_name = scan_layer.file_name();
let file_size = scan_layer.file_size();
let sha2_256 = match scan_layer.sha2_256() {
Ok(hash) => hash,
// Return CL_VIRUS to preserve the match, despite the error in this handler.
Err(_) => return cl_error_t::CL_VIRUS,
};
// Get the last match name
let mut match_out: *const c_char = std::ptr::null();
let cl_result = unsafe { clamav_sys::cl_scan_layer_get_last_alert(layer, &mut match_out) };
if cl_result != cl_error_t::CL_SUCCESS {
// Return CL_VIRUS to preserve the match, despite the error in this handler.
return cl_error_t::CL_VIRUS;
}
let match_name = if match_out.is_null() {
String::from("Unknown")
} else {
unsafe { CStr::from_ptr(match_out) }
.to_string_lossy()
.into_owned()
};
let match_logic = cxt
.match_logic
.as_ref()
.and_then(|logic| logic.downcast_ref::<Box<MatchLogic>>());
if let Some(logic) = match_logic {
decision =
match invoke_scan_logic(logic.as_ref(), &mut scan_layer, cxt.scan_context, "match")
{
Ok(decision) => decision,
Err(err) => return err,
};
}
if decision == ScanLogicResult::Success || decision == ScanLogicResult::Trust {
// The decision is to ignore the match or trust the file, which means
// we do not want to report the match to the user, so we return early here
// without sending an event.
} else {
let _ = cxt.sender.blocking_send(ScanEvent::MatchFound {
entity_id: object_id,
ancestors: ancestor_ids,
sha2_256,
file_name,
file_size,
file_type: file_type.into(),
match_name,
});
}
}
scan_logic_result_to_cl(decision)
}
pub(crate) unsafe extern "C" fn engine_callback_file_type(
layer: *mut clamav_sys::cl_scan_layer_t,
context: *mut c_void,
) -> cl_error_t {
let mut decision = ScanLogicResult::Success;
if let Some(cxt) = context.cast::<ScanCbContext>().as_ref() {
let mut scan_layer = ScanLayer::new(layer);
if scan_layer.fmap().is_err() {
return cl_error_t::CL_SUCCESS;
}
let object_id = match scan_layer.object_id() {
Ok(id) => id,
Err(_) => return cl_error_t::CL_SUCCESS,
};
let file_type = match scan_layer.type_() {
Ok(ft) => ft,
Err(_) => return cl_error_t::CL_SUCCESS,
};
let ancestor_ids = match scan_layer.ancestor_ids() {
Ok(ids) => ids,
Err(_) => return cl_error_t::CL_SUCCESS,
};
let file_name = scan_layer.file_name();
let file_size = scan_layer.file_size();
// Run the user-defined file-type logic, if it exists.
let file_type_logic = cxt
.file_type_logic
.as_ref()
.and_then(|logic| logic.downcast_ref::<Box<FileTypeLogic>>());
if let Some(logic) = file_type_logic {
decision = match invoke_scan_logic(
logic.as_ref(),
&mut scan_layer,
cxt.scan_context,
"file-type",
) {
Ok(decision) => decision,
Err(err) => return err,
};
}
let _ = cxt.sender.blocking_send(ScanEvent::FileType {
entity_id: object_id,
ancestors: ancestor_ids,
file_name,
file_size,
file_type: file_type.into(),
});
}
scan_logic_result_to_cl(decision)
}
pub(crate) unsafe extern "C" fn engine_callback_pre_scan(
layer: *mut clamav_sys::cl_scan_layer_t,
context: *mut c_void,
) -> cl_error_t {
let mut decision = ScanLogicResult::Success;
if let Some(cxt) = context.cast::<ScanCbContext>().as_ref() {
let mut scan_layer = ScanLayer::new(layer);
if scan_layer.fmap().is_err() {
return cl_error_t::CL_SUCCESS;
}
let object_id = match scan_layer.object_id() {
Ok(id) => id,
Err(_) => return cl_error_t::CL_SUCCESS,
};
let file_type = match scan_layer.type_() {
Ok(ft) => ft,
Err(_) => return cl_error_t::CL_SUCCESS,
};
let ancestor_ids = match scan_layer.ancestor_ids() {
Ok(ids) => ids,
Err(_) => return cl_error_t::CL_SUCCESS,
};
let file_name = scan_layer.file_name();
let file_size = scan_layer.file_size();
let sha2_256 = match scan_layer.sha2_256() {
Ok(hash) => hash,
Err(_) => return cl_error_t::CL_SUCCESS,
};
// Run the user-defined pre-scan logic, if it exists.
// This can be used for custom decisions or side effects before emitting the PreScan event.
let pre_scan_logic = cxt
.pre_scan_logic
.as_ref()
.and_then(|logic| logic.downcast_ref::<Box<PreScanLogic>>());
if let Some(logic) = pre_scan_logic {
decision = match invoke_scan_logic(
logic.as_ref(),
&mut scan_layer,
cxt.scan_context,
"pre-scan",
) {
Ok(decision) => decision,
Err(err) => return err,
};
}
let _ = cxt.sender.blocking_send(ScanEvent::PreScan {
entity_id: object_id,
ancestors: ancestor_ids,
sha2_256,
file_name,
file_size,
file_type: file_type.into(),
});
}
scan_logic_result_to_cl(decision)
}
pub(crate) unsafe extern "C" fn engine_callback_post_scan(
layer: *mut clamav_sys::cl_scan_layer_t,
context: *mut c_void,
) -> cl_error_t {
let mut decision = ScanLogicResult::Success;
if let Some(cxt) = context.cast::<ScanCbContext>().as_ref() {
let mut scan_layer = ScanLayer::new(layer);
if scan_layer.fmap().is_err() {
return cl_error_t::CL_SUCCESS;
}
let object_id = match scan_layer.object_id() {
Ok(id) => id,
Err(_) => return cl_error_t::CL_SUCCESS,
};
let file_type = match scan_layer.type_() {
Ok(ft) => ft,
Err(_) => return cl_error_t::CL_SUCCESS,
};
let ancestor_ids = match scan_layer.ancestor_ids() {
Ok(ids) => ids,
Err(_) => return cl_error_t::CL_SUCCESS,
};
let file_name = scan_layer.file_name();
let file_size = scan_layer.file_size();
let sha2_256 = match scan_layer.sha2_256() {
Ok(hash) => hash,
Err(_) => return cl_error_t::CL_SUCCESS,
};
let post_scan_logic = cxt
.post_scan_logic
.as_ref()
.and_then(|logic| logic.downcast_ref::<Box<PostScanLogic>>());
if let Some(logic) = post_scan_logic {
decision = match invoke_scan_logic(
logic.as_ref(),
&mut scan_layer,
cxt.scan_context,
"post-scan",
) {
Ok(decision) => decision,
Err(err) => return err,
};
}
let _ = cxt.sender.blocking_send(ScanEvent::PostScan {
entity_id: object_id,
ancestors: ancestor_ids,
sha2_256,
file_name,
file_size,
file_type: file_type.into(),
});
}
scan_logic_result_to_cl(decision)
}
#[cfg(test)]
mod tests {
use crate::{
callback::{EngineCallback, ScanLogicResult},
engine::{Engine, ScanEvent, ScanResult},
fmap::Fmap,
scan_settings::{GeneralFlags, ParseFlags, ScanSettings},
};
use sha2::{Digest, Sha256};
use std::{
fs::{self, File},
io::Cursor,
io::Write,
path::Path,
sync::{Arc, Mutex},
};
use tempfile::{tempdir, Builder};
use tokio_stream::StreamExt;
use zip::{write::SimpleFileOptions, CompressionMethod, ZipWriter};
const TEST_DATABASES_PATH: &str = "test_data/database/";
fn scan_settings() -> ScanSettings {
let mut settings = ScanSettings::default();
settings.set_parse(&ParseFlags::all());
settings.set_general(&GeneralFlags::CL_SCAN_GENERAL_HEURISTICS);
settings
}
async fn configured_engine() -> Engine {
crate::initialize().expect("initialize should succeed");
let engine = Engine::new();
engine
.load_databases(TEST_DATABASES_PATH)
.await
.expect("database load should succeed");
engine
.compile()
.await
.expect("engine compile should succeed");
engine
}
async fn scan_and_collect_events(
engine: &Engine,
target: Fmap,
filename: Option<&str>,
) -> Vec<ScanEvent> {
let mut stream = engine
.scan(target, filename, None, None, None, scan_settings(), None)
.expect("scan setup should succeed");
let mut events = Vec::new();
while let Some(event) = stream.next().await {
events.push(event);
}
events
}
fn fixture_metadata(path: &str) -> (String, usize, String) {
let bytes = fs::read(path).expect("fixture should be readable");
let file_name = Path::new(path)
.file_name()
.expect("fixture path should have file name")
.to_string_lossy()
.into_owned();
let sha2_256 = Sha256::digest(&bytes)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
(file_name, bytes.len(), sha2_256)
}
fn stored_zip_bytes(entry_name: &str, contents: &[u8]) -> Vec<u8> {
let cursor = Cursor::new(Vec::new());
let mut writer = ZipWriter::new(cursor);
let options = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
writer
.start_file(entry_name, options)
.expect("zip entry should be created");
writer
.write_all(contents)
.expect("zip contents should be written");
writer
.finish()
.expect("zip archive should be finalized")
.into_inner()
}
fn write_test_signature() -> tempfile::NamedTempFile {
let signature = b"naughty_file_test;Engine:81-255,Target:0;0;6e617567687479\n";
let mut db_file = Builder::new()
.prefix("match_callback_")
.suffix(".ldb")
.tempfile_in(TEST_DATABASES_PATH)
.expect("temporary database file creation should succeed");
db_file
.write_all(signature)
.expect("writing signature to temp file should succeed");
db_file
.flush()
.expect("flushing signature to temp file should succeed");
db_file
}
fn write_sha256_signature(
sha2_256: &str,
file_size: usize,
name: &str,
) -> tempfile::NamedTempFile {
let signature = format!("{sha2_256}:{file_size}:{name}\n");
let mut db_file = Builder::new()
.prefix("match_callback_")
.suffix(".hsb")
.tempfile_in(TEST_DATABASES_PATH)
.expect("temporary hash database file creation should succeed");
db_file
.write_all(signature.as_bytes())
.expect("writing signature to temp file should succeed");
db_file
.flush()
.expect("flushing signature to temp file should succeed");
db_file
}
fn pre_scan_operation(hit: Arc<Mutex<bool>>) -> Box<crate::callback::PreScanLogic> {
Box::new(
move |_scan_layer: &mut crate::callback::ScanLayer, _scan_context| {
*hit.lock().unwrap() = true;
// Return Success here to keep scanning.
ScanLogicResult::Success
},
)
}
fn pre_scan_trust_operation(hit: Arc<Mutex<bool>>) -> Box<crate::callback::PreScanLogic> {
Box::new(
move |_scan_layer: &mut crate::callback::ScanLayer, _scan_context| {
*hit.lock().unwrap() = true;
// Return Trust here to stop scanning the current layer, and mark the result as trusted.
// The parent layer will not be marked as trusted, and the scan will continue.
ScanLogicResult::Trust
},
)
}
fn post_scan_operation(hit: Arc<Mutex<bool>>) -> Box<crate::callback::PostScanLogic> {
Box::new(
move |_scan_layer: &mut crate::callback::ScanLayer, _scan_context| {
*hit.lock().unwrap() = true;
// Return Success here to keep scanning.
ScanLogicResult::Success
},
)
}
fn file_type_operation(
hit: Arc<Mutex<bool>>,
observed_file_type: Arc<Mutex<Option<String>>>,
) -> Box<crate::callback::FileTypeLogic> {
Box::new(
move |scan_layer: &mut crate::callback::ScanLayer, _scan_context| {
*observed_file_type.lock().unwrap() =
Some(scan_layer.type_().expect("file type should be available"));
*hit.lock().unwrap() = true;
// Return Success here to keep scanning.
ScanLogicResult::Success
},
)
}
fn match_operation(
hit: Arc<Mutex<bool>>,
copied_data: Arc<Mutex<Option<Vec<u8>>>>,
) -> Box<crate::callback::MatchLogic> {
Box::new(
move |scan_layer: &mut crate::callback::ScanLayer, _scan_context| {
*hit.lock().unwrap() = true;
*copied_data.lock().unwrap() = Some(
scan_layer
.data(0, 0)
.expect("data retrieval should succeed")
.to_vec(),
);
// Return Match here to agree with the match, so it isn't dropped.
ScanLogicResult::Match
},
)
}
// Goal: prove that a registered pre-scan callback runs for a simple file scan.
// Strategy: scan a known-good text fixture, assert the emitted PreScan event
// metadata matches the fixture, confirm the final result is clean, and check
// that the callback flipped its shared hit flag.
#[tokio::test]
async fn pre_scan_callback() {
let hit = Arc::new(Mutex::new(false));
let fixture_path = "test_data/files/good_file";
let (file_name, file_size, sha2_256) = fixture_metadata(fixture_path);
crate::initialize().expect("initialize should succeed");
// crate::debug();
let mut engine = configured_engine().await;
engine.register_callback(EngineCallback::PreScan, pre_scan_operation(hit.clone()));
let events = scan_and_collect_events(
&engine,
Fmap::try_from(File::open(fixture_path).expect("opening good_file should succeed"))
.expect("file-backed fmap creation should succeed"),
Some(&file_name),
)
.await;
let pre_scan_event = events
.iter()
.find(|event| matches!(event, ScanEvent::PreScan { .. }))
.expect("pre-scan event should be emitted");
let ScanEvent::PreScan {
entity_id,
ancestors,
sha2_256: event_sha2_256,
file_name: event_file_name,
file_size: event_file_size,
file_type,
} = pre_scan_event
else {
panic!("pre-scan event should match the expected variant");
};
assert_eq!(*entity_id, 0, "entity id should be the root layer");
assert_eq!(*ancestors, Vec::<u64>::new(), "ancestors should be empty");
assert_eq!(
*event_sha2_256, sha2_256,
"sha2-256 should match fixture content"
);
assert_eq!(
*event_file_name,
Some(file_name),
"file name should match the scanned file name"
);
assert_eq!(
*event_file_size, file_size,
"file size should match fixture size"
);
assert_eq!(
*file_type, "CL_TYPE_TEXT_ASCII",
"file type should be ASCII text"
);
assert!(
matches!(
events.last(),
Some(ScanEvent::Result(Ok(ScanResult::NothingFound)))
),
"scan should finish with no matches found"
);
assert!(
*hit.lock().unwrap(),
"registered pre-scan callback should run"
);
}
// Goal: prove that returning Trust from the root pre-scan callback marks the
// final scan result as Trusted.
// Strategy: register a pre-scan callback that always returns Trust, verify
// the root PreScan event metadata, and assert the terminal Result event is
// ScanResult::Trusted.
#[tokio::test]
async fn pre_scan_trust_returns_trusted_result() {
let hit = Arc::new(Mutex::new(false));
let fixture_path = "test_data/files/good_file";
let (file_name, file_size, sha2_256) = fixture_metadata(fixture_path);
crate::initialize().expect("initialize should succeed");
let mut engine = configured_engine().await;
engine.register_callback(
EngineCallback::PreScan,
pre_scan_trust_operation(hit.clone()),
);
let events = scan_and_collect_events(
&engine,
Fmap::try_from(File::open(fixture_path).expect("opening good_file should succeed"))
.expect("file-backed fmap creation should succeed"),
Some(&file_name),
)
.await;
let pre_scan_event = events
.iter()
.find(|event| matches!(event, ScanEvent::PreScan { .. }))
.expect("pre-scan event should be emitted");
let ScanEvent::PreScan {
entity_id,
ancestors,
sha2_256: event_sha2_256,
file_name: event_file_name,
file_size: event_file_size,
file_type,
} = pre_scan_event
else {
panic!("pre-scan event should match the expected variant");
};
assert_eq!(*entity_id, 0, "entity id should be the root layer");
assert_eq!(*ancestors, Vec::<u64>::new(), "ancestors should be empty");
assert_eq!(
*event_sha2_256, sha2_256,
"sha2-256 should match fixture content"
);
assert_eq!(
*event_file_name,
Some(file_name),
"file name should match the scanned file name"
);
assert_eq!(
*event_file_size, file_size,
"file size should match fixture size"
);
assert_eq!(
*file_type, "CL_TYPE_TEXT_ASCII",
"file type should be ASCII text"
);
assert!(
matches!(
events.last(),
Some(ScanEvent::Result(Ok(ScanResult::Trusted)))
),
"returning Trust from the pre-scan callback should end the scan as trusted"
);
assert!(
*hit.lock().unwrap(),
"registered pre-scan trust callback should run"
);
}
#[tokio::test]
async fn panic_in_callback_is_caught_and_aborts_scan() {
let fixture_path = "test_data/files/good_file";
let (file_name, _file_size, _sha2_256) = fixture_metadata(fixture_path);
crate::initialize().expect("initialize should succeed");
let mut engine = configured_engine().await;
engine.register_callback(
EngineCallback::PreScan,
Box::new(
|_scan_layer: &mut crate::callback::ScanLayer, _scan_context| {
panic!("callback panic should be caught inside the FFI shim");
},
),
);
let events = scan_and_collect_events(
&engine,
Fmap::try_from(File::open(fixture_path).expect("opening good_file should succeed"))
.expect("file-backed fmap creation should succeed"),
Some(&file_name),
)
.await;
assert!(
!events
.iter()
.any(|event| matches!(event, ScanEvent::PreScan { .. })),
"a panicking callback should abort before emitting the callback event"
);
assert!(
matches!(events.as_slice(), [ScanEvent::Result(_)]),
"a panicking callback should still terminate through the normal result channel instead of unwinding across FFI"
);
}
// Goal: prove that the file-type callback runs and sees the layer type that
// libclamav reports for the scanned file.
// Strategy: capture the type string from the callback, verify the emitted
// FileType event fields match the fixture, and assert both the observed type
// and the event type are CL_TYPE_TEXT_ASCII.
#[tokio::test]
async fn file_type_callback() {
let hit = Arc::new(Mutex::new(false));
let observed_file_type = Arc::new(Mutex::new(None));
let fixture_path = "test_data/files/good_file";
let (file_name, file_size, _sha2_256) = fixture_metadata(fixture_path);
crate::initialize().expect("initialize should succeed");
// crate::debug();
let mut engine = configured_engine().await;
engine.register_callback(
EngineCallback::FileType,
file_type_operation(hit.clone(), observed_file_type.clone()),
);
let events = scan_and_collect_events(
&engine,
Fmap::try_from(File::open(fixture_path).expect("opening good_file should succeed"))
.expect("file-backed fmap creation should succeed"),
Some(&file_name),
)
.await;
let file_type_event = events
.iter()
.find(|event| matches!(event, ScanEvent::FileType { .. }))
.expect("file-type event should be emitted");
let ScanEvent::FileType {
entity_id,
ancestors,
file_name: event_file_name,
file_size: event_file_size,
file_type,
} = file_type_event
else {
panic!("file-type event should match the expected variant");
};
assert_eq!(*entity_id, 0, "entity id should be the root layer");
assert_eq!(*ancestors, Vec::<u64>::new(), "ancestors should be empty");
assert_eq!(
*event_file_name,
Some(file_name),
"file name should match the scanned file name"
);