malwaredb-virustotal 0.2.1

Logic and datatypes for interacting with VirusTotal
Documentation
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
use std::fmt::{Debug, Display, Formatter};
use std::ops::{Add, BitOr, Shl, Shr};

use chrono::{DateTime, Days, Utc};

/// File types available for searching
/// See <https://docs.virustotal.com/docs/file-search-modifiers> for the complete list of flags.
#[derive(Copy, Clone, Debug, Hash)]
pub enum FileType {
    /// Any executable
    AnyExecutable,

    /// Android .apk application package
    Apk,

    /// Android application
    Android,

    /// Non-Linux Unix file, Common Object File Format
    Coff,

    /// MS-DOS command file
    Com,

    /// Microsoft Word document, any format
    Word,

    /// Microsoft Word, older DOCFILE format
    Doc,

    /// Microsoft Word, newer Zip & XML-based format
    Docx,

    /// MS-DOS
    Dos,

    /// ELFs (Executable and Linkable File), used on Unix or Unix-like operating systems
    Elf,

    /// Microsoft Excel spreadsheet, any format
    Excel,

    /// Microsoft Excel, older DOCFILE format
    Xls,

    /// Microsoft Excel, newer Zip & XML-based format
    Xlsx,

    /// ELFs, but for Linux
    Linux,

    /// Debian package for Linux, typically Debian, Ubuntu, Mint, others
    Deb,

    /// RPM paclage for Linux, typically Redhat, CentOS, others
    Rpm,

    /// New Executable <https://en.wikipedia.org/wiki/New_Executable>
    /// This is an old format for Windows 1.0 - Windows 95/98, OS/2
    Ne,

    /// New Executable <https://en.wikipedia.org/wiki/New_Executable>, applications only
    /// This is an old format for Windows 1.0 - Windows 95/98, OS/2
    NeExe,

    /// New Executable <https://en.wikipedia.org/wiki/New_Executable>, shared library only
    /// This is an old format for Windows 1.0 - Windows 95/98, OS/2
    NeDll,

    /// Program which installs some other program
    Installer,

    /// Mach-O, for macOS, iOS, etc
    MachO,

    /// Mac DMG disk image
    MacDmg,

    /// Microsoft Office
    MsOffice,

    /// Adobe PDF (Portable Document Format)
    Pdf,

    /// Rich Text Format (RTF) documents
    Rtf,

    /// PE32 (Portable Executable) files, .exe and .dll
    PE32,

    /// PE32 files, just .dll
    PeDll,

    /// PE32 files, just .exe
    PeExe,

    /// 16-bit Windows (.exe or .dll, old Windows)
    Win16,

    /// 32-bit Windows (.exe or .dll, current Windows)
    Win32,

    /// Any PE32 file which could run on Windows
    Windows,

    /// Windows installer file
    WindowsMSI,
}

impl Display for FileType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            FileType::AnyExecutable => write!(f, "type:executable"),
            FileType::Apk => write!(f, "type:apk"),
            FileType::Android => write!(f, "type:android"),
            FileType::Coff => write!(f, "type:coff"),
            FileType::Com => write!(f, "type:com"),
            FileType::Word => write!(f, "type:word"),
            FileType::Doc => write!(f, "type:doc"),
            FileType::Docx => write!(f, "type:docx"),
            FileType::Dos => write!(f, "type:dos"),
            FileType::Elf => write!(f, "type:elf"),
            FileType::Deb => write!(f, "type:deb"),
            FileType::Rpm => write!(f, "type:rpm"),
            FileType::Excel => write!(f, "type:excel"),
            FileType::Xls => write!(f, "type:xls"),
            FileType::Xlsx => write!(f, "type:xlsx"),
            FileType::Linux => write!(f, "type:linux"),
            FileType::Ne => write!(f, "type:ne"),
            FileType::Installer => write!(f, "type:installer"),
            FileType::NeExe => write!(f, "type:neexe"),
            FileType::NeDll => write!(f, "type:nedll"),
            FileType::MachO => write!(f, "type:macho"),
            FileType::MacDmg => write!(f, "type:dmg"),
            FileType::MsOffice => write!(f, "type:msoffice"),
            FileType::Pdf => write!(f, "type:pdf"),
            FileType::Rtf => write!(f, "type:rtf"),
            FileType::PE32 => write!(f, "type:peexe OR type:pedll"),
            FileType::PeDll => write!(f, "type:pedll"),
            FileType::PeExe => write!(f, "type:peexe"),
            FileType::Win16 => write!(f, "type:win16"),
            FileType::Win32 => write!(f, "type:win32"),
            FileType::Windows => write!(f, "type:windows"),
            FileType::WindowsMSI => write!(f, "type:msi"),
        }
    }
}

impl BitOr for FileType {
    type Output = String;

    fn bitor(self, rhs: Self) -> Self::Output {
        format!("{self} OR {rhs}")
    }
}

/// [Vec<FileType>] with [Display] already implemented.
#[derive(Clone, Debug, Hash)]
pub struct FileTypes(pub Vec<FileType>);

impl Display for FileTypes {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let combined = self
            .0
            .iter()
            .map(|ft| ft.to_string())
            .collect::<Vec<String>>()
            .join(" OR ");
        write!(f, "{combined}")
    }
}

/// File attributes, many are file-type specific. Be sure to not use a [Tag] which is not
/// appropriate for the [FileType] being sought.
#[derive(Copy, Clone, Debug, Hash)]
pub enum Tag {
    /// PE32 file which uses the .Net Framework (CLR)
    DotNetAssembly,

    /// If the executable is 64-bit
    Executable64bit,

    /// PE32 file runs in the EFI environment
    ExecutableEFI,

    /// If the PE32 or Mach-O file has an embedded signature
    ExecutableSigned,

    /// If the sample makes use of a known exploit
    Exploit,

    /// Sample was caught in the wild with a honeypot system
    Honeypot,

    /// Microsoft Office file with macro(s)
    MSOfficeMacro,

    /// PDF document which does something when viewed
    PdfAutoAction,

    /// PDF document with some other file(s) embedded
    PdfEmbeddedFile,

    /// PDF document with a fillable form
    PdfForm,

    /// PDF document with embedded Javascript
    PdfJs,

    /// PDF document which executes Javascript when opened
    PdfLaunchAction,
}

impl Display for Tag {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Tag::DotNetAssembly => write!(f, "tag:assembly"),
            Tag::Executable64bit => write!(f, "tag:64bits"),
            Tag::ExecutableEFI => write!(f, "tag:efi"),
            Tag::ExecutableSigned => write!(f, "tag:signed"),
            Tag::Exploit => write!(f, "tag:exploit"),
            Tag::Honeypot => write!(f, "tag:honeypot"),
            Tag::MSOfficeMacro => write!(f, "tag:macros"),
            Tag::PdfAutoAction => write!(f, "tag:autoaction"),
            Tag::PdfEmbeddedFile => write!(f, "tag:file-embedded"),
            Tag::PdfForm => write!(f, "tag:acroform"),
            Tag::PdfJs => write!(f, "tag:js-embedded"),
            Tag::PdfLaunchAction => write!(f, "tag:launch-action"),
        }
    }
}

impl BitOr for Tag {
    type Output = String;

    fn bitor(self, rhs: Self) -> Self::Output {
        format!("{self} {rhs}")
    }
}

/// [Vec<Tag>] with [Display] already implemented.
#[derive(Clone, Debug, Hash)]
pub struct Tags(pub Vec<Tag>);

impl Display for Tags {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let combined = self
            .0
            .iter()
            .map(|t| t.to_string())
            .collect::<Vec<String>>()
            .join(" ");
        write!(f, "{combined}")
    }
}

/// Antivirus hit results, with optional upper bound.
#[derive(Copy, Clone, Debug, Hash)]
pub struct Positives {
    /// Minimum number of hits
    pub min: u32,

    /// Optional upper bound of amount of antivirus hits
    pub max: Option<u32>,

    /// Exact, [Positives::min] won't have `+`
    pub exact: bool,
}

impl Positives {
    /// Specify some minimum amount of antivirus hits, but no maximum
    pub const fn min(min: u32) -> Self {
        Positives {
            min,
            max: None,
            exact: false,
        }
    }

    /// Specify a minimum and maximum antivirus hits
    pub const fn min_max(min: u32, max: u32) -> Self {
        Positives {
            min,
            max: Some(max),
            exact: false,
        }
    }
}

/// No VirusTotal hits, but benign today doesn't mean benign tomorrow.
pub const BENIGN: Positives = Positives {
    min: 0,
    max: Some(0),
    exact: true,
};

impl Default for Positives {
    fn default() -> Self {
        // This is definitely arbitrary, but 5 or more hits probably is something not wanted
        // on a computer system
        Positives {
            min: 5,
            max: None,
            exact: false,
        }
    }
}

impl Display for Positives {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if self.exact {
            return write!(f, "positives:{}", self.min);
        }

        write!(f, "positives:{}+", self.min)?;

        if let Some(max) = self.max {
            write!(f, " positives:{max}-")
        } else {
            write!(f, "")
        }
    }
}

/// Find files submitted on or after a specific date, or within a date range
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct FirstSubmission {
    /// First seen date & time
    pub first: DateTime<Utc>,

    /// Second date & time for a range
    pub second: Option<DateTime<Utc>>,

    /// If true, then only find files submitted at the first date
    pub exact: bool,

    /// For date vs datetime. Use only the specified formats [FirstSubmission::FORMAT_DATE] or
    /// [FirstSubmission::FORMATE_DATE_TIME], otherwise there will likely be errors or empty results
    pub format: &'static str,
}

impl FirstSubmission {
    /// Year-Month-Day format for courser file submission selection
    pub const FORMAT_DATE: &'static str = "%Y-%m-%d";
    /// Year-Month-Day Hour-Minute-Second for finer file submission selection
    pub const FORMAT_DATETIME: &'static str = "%Y-%m-%dT%H:%M:%S";

    /// Only submitted at a specific date
    pub fn at_date(start: DateTime<Utc>) -> Self {
        Self {
            first: start,
            second: None,
            exact: true,
            format: Self::FORMAT_DATE,
        }
    }

    /// Only submitted at a specific date and time
    pub fn at_datetime(start: DateTime<Utc>) -> Self {
        Self {
            first: start,
            second: None,
            exact: true,
            format: Self::FORMAT_DATETIME,
        }
    }

    /// First submitted on or after a specific date
    pub fn from_date(start: DateTime<Utc>) -> Self {
        Self {
            first: start,
            second: None,
            exact: false,
            format: Self::FORMAT_DATE,
        }
    }

    /// First submitted on or after a specific date and time
    pub fn from_datetime(start: DateTime<Utc>) -> Self {
        Self {
            first: start,
            second: None,
            exact: false,
            format: Self::FORMAT_DATETIME,
        }
    }

    /// Builder: Set the end date
    pub fn until_date(self, end: DateTime<Utc>) -> Self {
        Self {
            first: self.first,
            second: Some(end),
            exact: false,
            format: self.format,
        }
    }

    /// Submitted on or after some [Days] ago
    pub fn days(days: u32) -> Self {
        let start = Utc::now() - Days::new(days as u64);
        Self {
            first: start,
            second: None,
            exact: false,
            format: Self::FORMAT_DATE,
        }
    }
}

impl Display for FirstSubmission {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if self.exact {
            return write!(f, "fs:{}", self.first.format(self.format));
        }

        write!(f, "fs:{}+", self.first.format(self.format))?;

        if let Some(second) = self.second {
            write!(f, " fs:{}-", second.format(self.format))
        } else {
            write!(f, "")
        }
    }
}

impl Add<Days> for FirstSubmission {
    type Output = FirstSubmission;

    /// Add [Days] to the end date, creating relative to start if not present
    fn add(self, rhs: Days) -> Self::Output {
        let end = if let Some(end) = self.second {
            end + rhs
        } else {
            self.first + rhs
        };

        Self {
            first: self.first,
            second: Some(end),
            exact: self.exact,
            format: self.format,
        }
    }
}

impl Shl<Days> for FirstSubmission {
    type Output = Self;

    /// Shift both the start and end dates forward by some amount of [Days]. Does not create
    /// and end date if it doesn't exist.
    #[allow(clippy::suspicious_arithmetic_impl)]
    fn shl(self, rhs: Days) -> Self::Output {
        let start = self.first + rhs;
        let end = self.second.map(|second| second + rhs);

        Self {
            first: start,
            second: end,
            exact: self.exact,
            format: self.format,
        }
    }
}

impl Shr<Days> for FirstSubmission {
    type Output = Self;

    /// Shift both the start and dates backward by some amount of [Days]. Does not create
    /// and end date if it doesn't exist.
    #[allow(clippy::suspicious_arithmetic_impl)]
    fn shr(self, rhs: Days) -> Self::Output {
        let start = self.first - rhs;
        let end = self.second.map(|second| second - rhs);

        Self {
            first: start,
            second: end,
            exact: self.exact,
            format: self.format,
        }
    }
}

impl Add<FileType> for Positives {
    type Output = String;
    fn add(self, rhs: FileType) -> Self::Output {
        format!("{rhs} {self}")
    }
}

impl Add<Positives> for FileType {
    type Output = String;
    fn add(self, rhs: Positives) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<Tag> for FileType {
    type Output = String;
    fn add(self, rhs: Tag) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<Tags> for FileType {
    type Output = String;
    fn add(self, rhs: Tags) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<FirstSubmission> for FileType {
    type Output = String;
    fn add(self, rhs: FirstSubmission) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<Positives> for Tag {
    type Output = String;
    fn add(self, rhs: Positives) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<Positives> for Tags {
    type Output = String;
    fn add(self, rhs: Positives) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<FirstSubmission> for Tag {
    type Output = String;
    fn add(self, rhs: FirstSubmission) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<FileTypes> for Positives {
    type Output = String;
    fn add(self, rhs: FileTypes) -> Self::Output {
        format!("{rhs} {self}")
    }
}

impl Add<Positives> for FileTypes {
    type Output = String;
    fn add(self, rhs: Positives) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<String> for FileTypes {
    type Output = String;
    fn add(self, rhs: String) -> Self::Output {
        format!("{self} {rhs}")
    }
}
impl Add<FirstSubmission> for FileTypes {
    type Output = String;
    fn add(self, rhs: FirstSubmission) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<String> for Tags {
    type Output = String;

    fn add(self, rhs: String) -> Self::Output {
        format!("{rhs} {self}")
    }
}

impl Add<String> for Tag {
    type Output = String;

    fn add(self, rhs: String) -> Self::Output {
        format!("{rhs} {self}")
    }
}

impl Add<FirstSubmission> for Tags {
    type Output = String;

    fn add(self, rhs: FirstSubmission) -> Self::Output {
        format!("{rhs} {self}")
    }
}

impl Add<Tag> for String {
    type Output = String;

    fn add(self, rhs: Tag) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<Tags> for String {
    type Output = String;

    fn add(self, rhs: Tags) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<FileType> for String {
    type Output = String;

    fn add(self, rhs: FileType) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<FirstSubmission> for String {
    type Output = String;

    fn add(self, rhs: FirstSubmission) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<FileType> for FirstSubmission {
    type Output = String;

    fn add(self, rhs: FileType) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<Positives> for FirstSubmission {
    type Output = String;

    fn add(self, rhs: Positives) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<String> for FirstSubmission {
    type Output = String;

    fn add(self, rhs: String) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<Tag> for FirstSubmission {
    type Output = String;

    fn add(self, rhs: Tag) -> Self::Output {
        format!("{self} {rhs}")
    }
}

impl Add<Tags> for FirstSubmission {
    type Output = String;

    fn add(self, rhs: Tags) -> Self::Output {
        format!("{self} {rhs}")
    }
}

#[cfg(test)]
mod tests {
    use chrono::TimeZone;

    use super::*;

    #[test]
    fn benign() {
        assert_eq!(BENIGN.to_string(), "positives:0");
    }

    #[test]
    fn types_positives() {
        let types: String = FileTypes(vec![FileType::MachO, FileType::Dos, FileType::WindowsMSI])
            + Positives::default()
            + Tag::ExecutableSigned;
        assert_eq!(
            types,
            "type:macho OR type:dos OR type:msi positives:5+ tag:signed"
        );
    }

    #[test]
    fn first_submission() {
        let first =
            FirstSubmission::at_datetime(Utc.with_ymd_and_hms(2015, 5, 15, 10, 20, 30).unwrap());
        assert_eq!(first.to_string(), "fs:2015-05-15T10:20:30");

        let first =
            FirstSubmission::at_datetime(Utc.with_ymd_and_hms(2015, 5, 15, 10, 20, 30).unwrap());
        let first = first.until_date(Utc.with_ymd_and_hms(2015, 12, 30, 23, 59, 59).unwrap());
        assert_eq!(
            first.to_string(),
            "fs:2015-05-15T10:20:30+ fs:2015-12-30T23:59:59-"
        );

        let shifted_forward = first.clone() << Days::new(1);
        assert_eq!(
            shifted_forward.to_string(),
            "fs:2015-05-16T10:20:30+ fs:2015-12-31T23:59:59-"
        );

        let shifted_back = shifted_forward >> Days::new(1);
        assert_eq!(shifted_back, first);
    }
}