malware-modeler 0.1.0

Train logisitic regression models for benign vs. malicious files based on byte n-grams and published research, plus related tools.
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
// SPDX-License-Identifier: Apache-2.0

#![deny(clippy::all)]
//#![deny(clippy::cargo)]
#![deny(clippy::pedantic)]
#![forbid(unsafe_code)]

use std::fs::File;
use std::io::Write;
use std::num::NonZero;
use std::path::PathBuf;
use std::process::ExitCode;

use anyhow::{Result, bail, ensure};
use clap::{Command, CommandFactory, Parser, Subcommand, ValueHint};
use clap_complete::{Shell, generate};
use malware_modeler::crossval::{CrossValidation, CrossValidationReport, SelectionMetric};
use walkdir::WalkDir;

/// Malware Modeler
///
/// Create malicious vs benign models
#[derive(Parser)]
#[command(author, about, version = malware_modeler::VERSION)]
pub struct Args {
    /// Subcommands (with their own options)
    #[clap(subcommand)]
    cmd: Actions,

    /// Number of threads to use for parallel operations.
    #[clap(long, default_value_t = threads())]
    threads: usize,
}

#[inline]
fn threads() -> usize {
    std::thread::available_parallelism()
        .unwrap_or(NonZero::<usize>::MIN)
        .get()
}

#[derive(Subcommand)]
enum Actions {
    /// Find n-grams
    Ngram(Ngram),

    /// Create dataset from samples and existing n-grams file
    Dataset(Dataset),

    /// Convert between dataset file formats, using the file extension to detect file types
    DatasetConvert(DatasetConvert),

    /// Show some information about a dataset file
    DatasetInfo(DatasetInfo),

    /// Split an existing dataset file into a balanced training set and likely unbalanced testing set.
    DatasetSplit(DatasetSplit),

    /// Train a malware model
    Train(Train),

    /// Evaluate a dataset against a model
    Evaluate(Evaluate),

    /// Model operations
    Model(ModelInfo),

    /// Show type information or sort files by type with symbolic links and SHA-256 hashes.
    Types(Types),

    /// Check similarity between files using LZJD
    Similarity(Similarity),

    /// Unzip files from a Zip archive by the type, if the type is known
    SelectiveUnzip(SelectiveUnzip),

    /// Split a collection of files into training and testing
    Split(Split),

    /// What's inside that Zip file??
    ZipSummary(ZipSummary),

    /// Generate shell autocomplete script
    Generate(Generator),
}

/// Find n-grams
#[derive(Parser)]
struct Ngram {
    /// Directory containing benign and malicious samples
    #[arg(short, long, value_hint = ValueHint::DirPath)]
    path: PathBuf,

    /// Optional: specify the type of file to be processed.
    /// If not specified, the file type will be detected automatically.
    #[arg(short = 't', long = "type", ignore_case = true)]
    ftype: Option<malware_modeler::ftype::FileType>,

    /// Size of the byte ngram
    #[arg(short, default_value_t = 6)]
    n: u16,

    /// Max number of n-grams to keep
    #[arg(short, default_value_t = 10000)]
    k: usize,

    /// N-gram stride, an attempt to reduce similar n-grams by
    /// checking `hash(n-gram) % stride == 0`
    #[arg(short, long, default_value_t = 1)]
    stride: u16,

    /// Output n-grams path
    #[arg(short, long, value_hint = ValueHint::FilePath, default_value = "ngrams.txt")]
    output: PathBuf,

    /// Store the number of n-gram occurrences
    #[clap(short, long, short, action)]
    counts: bool,

    /// Show some additional information
    #[clap(long, default_value = "false", action)]
    verbose: bool,

    /// Skip unknowns, useful if type identification fails of it there's a mix of types.
    /// Note: this could go wrong if the expected file type isn't provided.
    #[clap(long, default_value = "false", action)]
    skip_unknowns: bool,
}

impl Ngram {
    fn execute(&self) -> Result<ExitCode> {
        ensure!(
            !self.output.exists(),
            "Refusing to overwrite existing n-grams file {}",
            self.output.display()
        );

        if self.k < 10 {
            eprintln!("N-Gram count must be at least 10, should be ~100k");
            return Ok(ExitCode::FAILURE);
        }
        if self.n < 2 {
            eprintln!("N-Gram size must be at least 2, should be >4");
            return Ok(ExitCode::FAILURE);
        }
        if self.stride == 0 {
            eprintln!("N-Gram stride must be greater than 0");
            return Ok(ExitCode::FAILURE);
        }

        let (mut ngrammer, skipped) = malware_modeler::ngram::Ngrammer::new(
            self.ftype,
            &self.path,
            self.n,
            self.k,
            self.stride,
            self.verbose,
            self.skip_unknowns,
        )?;
        ngrammer.find();
        println!(
            "{}-gramming skipped {skipped} files which weren't {} files.",
            self.n,
            ngrammer.ftype()
        );
        if ngrammer.ngrams().len() < self.k {
            println!(
                "Found {} n-grams, fewer than the {} requested.",
                ngrammer.ngrams().len(),
                self.k
            );
        }
        ngrammer.save(&self.output, self.counts)?;

        Ok(ExitCode::SUCCESS)
    }
}

/// Create dataset from samples and existing n-grams file
#[derive(Parser)]
struct Dataset {
    /// Directory containing malicious samples
    #[arg(short, long, value_hint = ValueHint::DirPath)]
    pub malicious: PathBuf,

    /// Directory containing benign samples
    #[arg(short, long, value_hint = ValueHint::DirPath)]
    pub benign: PathBuf,

    /// N-grams file for featurization
    #[arg(short, long, value_hint = ValueHint::FilePath)]
    pub ngrams: PathBuf,

    /// Output dataset file
    #[arg(short, long, value_hint = ValueHint::FilePath)]
    pub output: PathBuf,

    /// Show additional details
    #[arg(short, long, default_value_t = false)]
    pub verbose: bool,
}

impl Dataset {
    fn execute(&self) -> Result<ExitCode> {
        ensure!(
            !self.output.exists(),
            "Refusing to overwrite existing dataset file {}",
            self.output.display()
        );
        malware_modeler::dataset::Dataset::create_save_from_benign_malicious_files_and_ngrams(
            &self.malicious,
            &self.benign,
            &self.ngrams,
            &self.output,
            self.verbose,
        )?;

        Ok(ExitCode::SUCCESS)
    }
}

/// Convert between dataset file formats, using the file extension to detect file types
#[derive(Parser)]
struct DatasetConvert {
    /// Input file
    #[arg(short, long = "in", value_hint = ValueHint::FilePath)]
    pub input: PathBuf,

    /// Output file
    #[arg(short, long = "out", value_hint = ValueHint::FilePath)]
    pub output: PathBuf,

    /// Optionally provide a model, which is used to reduce the dataset by removing unneeded features.
    #[arg(short, long, value_hint = ValueHint::FilePath)]
    pub model: Option<PathBuf>,
}

impl DatasetConvert {
    fn execute(&self) -> Result<ExitCode> {
        if self.input.extension() == self.output.extension() && self.model.is_none() {
            eprintln!("Refusing to attempt 'conversion' between files with the same extension.");
            return Ok(ExitCode::FAILURE);
        }

        ensure!(
            !self.output.exists(),
            "Refusing to overwrite existing dataset file {}",
            self.output.display()
        );
        let mut dataset = malware_modeler::dataset::Dataset::load(&self.input)?;

        if let Some(model) = &self.model {
            let original = dataset.data.row_len();
            let model_contents = std::fs::read_to_string(model)?;
            let model: malware_modeler::model::LogisticRegression =
                serde_json::from_str(model_contents.as_str())?;
            let removed = dataset.reduce(&model)?.len();
            println!("Removed {removed} features from the original {original}");
        }

        dataset.save(&self.output)?;
        Ok(ExitCode::SUCCESS)
    }
}

/// Print some information about a dataset
#[derive(Parser)]
struct DatasetInfo {
    /// Path to a dataset file
    #[arg(value_hint = ValueHint::FilePath)]
    pub dataset: PathBuf,
}

impl DatasetInfo {
    fn execute(&self) -> Result<ExitCode> {
        let probe = malware_modeler::dataset::Dataset::probe(&self.dataset)?;
        println!("{probe}");

        Ok(ExitCode::SUCCESS)
    }
}

/// Split a dataset into a balanced training dataset and potentially unbalanced testing dataset
#[derive(Parser)]
struct DatasetSplit {
    /// Input file, which will not be altered.
    #[arg(short, long = "in", value_hint = ValueHint::FilePath)]
    pub input: PathBuf,

    /// Training dataset file
    #[arg(short, long = "train", value_hint = ValueHint::FilePath)]
    pub training: PathBuf,

    /// Testing dataset file
    #[arg(short = 'e', long = "test", value_hint = ValueHint::FilePath)]
    pub testing: PathBuf,

    /// The amount of data to be in the training set
    #[arg(short, long, default_value_t = 0.8)]
    pub ratio: f32,
}

impl DatasetSplit {
    fn execute(&self) -> Result<ExitCode> {
        ensure!(
            !self.training.exists(),
            "Refusing to overwrite existing dataset file {}",
            self.training.display()
        );
        ensure!(
            !self.testing.exists(),
            "Refusing to overwrite existing dataset file {}",
            self.testing.display()
        );

        let mut original = malware_modeler::dataset::Dataset::load(&self.input)?;
        let testing = original.split(self.ratio);

        original.save(&self.training)?;
        testing.save(&self.testing)?;

        Ok(ExitCode::SUCCESS)
    }
}

/// Train a malware vs benign model
#[derive(Parser)]
struct Train {
    /// Dataset for training
    #[arg(short, long, value_hint = ValueHint::FilePath)]
    pub dataset: PathBuf,

    /// Optional dataset for testing
    #[arg(short, long, value_hint = ValueHint::FilePath)]
    pub test: Option<PathBuf>,

    /// Output model path
    #[arg(short, long, value_hint = ValueHint::FilePath)]
    pub model: PathBuf,

    /// Number of iterations for training
    #[arg(short, long, default_value_t = 100)]
    pub epochs: u32,

    /// Learning rate. Keep it under roughly 8 divided
    /// by the features set in a typical row.
    #[arg(short = 'r', long = "lr", default_value_t = 0.001)]
    pub learning_rate: f32,

    /// L1 penalty to reduce features
    #[arg(short = '1', long = "l1", default_value_t = 0.1)]
    pub l1_penalty: f32,

    /// L2 penalty to prevent one n-gram feature becoming too influential
    #[arg(short = '2', long = "l2", default_value_t = 0.1)]
    pub l2_penalty: f32,

    /// Report the dataset's shape and projected memory use, then stop without loading it.
    #[arg(long, default_value_t = false)]
    pub dry_run: bool,

    /// Run stratified n-fold cross validation with this many folds, saving only the best
    /// fold's model. Each fold trains on label-balanced rows.
    #[arg(short = 'k', long, value_parser = clap::value_parser!(u16).range(2..))]
    pub folds: Option<u16>,

    /// Metric for picking the best cross validation fold: accuracy, precision, recall, f1, or auc
    #[arg(long, default_value_t = SelectionMetric::Auc, requires = "folds")]
    pub select_by: SelectionMetric,
}

impl Train {
    fn execute(&self) -> Result<ExitCode> {
        // Printed before loading: a dataset too large for the machine is otherwise only
        // discovered by the process being killed part way through, which says nothing about
        // how far off it was.
        match malware_modeler::dataset::Dataset::probe(&self.dataset) {
            Ok(probe) => println!("{probe}\n"),
            Err(e) => eprintln!("Could not probe {}: {e}", self.dataset.display()),
        }

        if self.dry_run {
            return Ok(ExitCode::SUCCESS);
        }

        ensure!(
            !self.model.exists(),
            "Refusing to overwrite existing model file {}",
            self.model.display()
        );

        if let Some(test_dataset) = &self.test
            && let Ok(probe) = malware_modeler::dataset::Dataset::probe(test_dataset)
        {
            println!("Test dataset:\n{probe}\n");
        }

        let mut dataset = malware_modeler::dataset::Dataset::load(&self.dataset)?;

        let test_dataset = if let Some(test_dataset) = &self.test {
            let test = malware_modeler::dataset::Dataset::load(test_dataset)?;
            ensure!(
                dataset.same_ngrams_ftype(&test),
                "Train and test datasets have different features or file type"
            );
            Some(test)
        } else {
            None
        };

        if let Some(folds) = self.folds {
            return self.cross_validate(&dataset, test_dataset.as_ref(), folds.into());
        }

        let mut model = malware_modeler::model::LogisticRegression::new(
            dataset.data.row_len(),
            self.learning_rate,
            self.l1_penalty,
            self.l2_penalty,
        );
        let run = match model.fit(self.epochs, &mut dataset, test_dataset.as_ref()) {
            Ok(run) => run,
            Err(error) => {
                eprintln!("Training failed: {error}");
                return Ok(ExitCode::FAILURE);
            }
        };
        println!("Training complete, final error {}", run.loss);
        print_feature_reduction(&model, run.features_removed);

        println!("\nPerformance on the training dataset:");
        print_performance_stats(&model.train_performance);

        if let Some(test) = &model.test_performance {
            println!("\nPerformance on the test dataset:");
            print_performance_stats(test);
        }

        model.save(&self.model)?;
        Ok(ExitCode::SUCCESS)
    }

    /// Train a model per fold, report them all, and save the best.
    ///
    /// The folds borrow the dataset's rows rather than copying them. If a separate test dataset
    /// was given, the best model's test performance is replaced with its performance on that,
    /// since it was not used to pick the model.
    fn cross_validate(
        &self,
        dataset: &malware_modeler::dataset::Dataset,
        test: Option<&malware_modeler::dataset::Dataset>,
        folds: usize,
    ) -> Result<ExitCode> {
        let cv = CrossValidation::new(dataset, folds)?;

        let mut results = Vec::with_capacity(folds);
        for index in 0..folds {
            println!("Fold {}/{folds}", index + 1);
            let result = match cv.run_fold(
                index,
                self.epochs,
                self.learning_rate,
                self.l1_penalty,
                self.l2_penalty,
            ) {
                Ok(result) => result,
                Err(error) => {
                    eprintln!("Training fold {} failed: {error}", index + 1);
                    return Ok(ExitCode::FAILURE);
                }
            };
            println!(
                "Trained on {} rows, tested on {}, final error {}",
                result.train_rows, result.test_rows, result.loss
            );
            print_feature_reduction(&result.model, result.features_removed);
            print_performance_stats(&result.test_performance);
            println!();
            results.push(result);
        }

        let report = CrossValidationReport::new(results, self.select_by)?;
        println!("{report}");

        let mut model = report.into_best();
        if let Some(test) = test {
            println!("\nBest model's performance on the test dataset:");
            let result = model.evaluate_dataset(test)?;
            print_confusion_matrix(&result);
            model.test_performance = Some(result.into());
        }

        model.save(&self.model)?;
        Ok(ExitCode::SUCCESS)
    }
}

/// Print how many features training dropped.
fn print_feature_reduction(model: &malware_modeler::model::LogisticRegression, removed: usize) {
    let reduced = model.weights.len();
    let original = reduced + removed;
    println!("Features reduced by {removed}: {original} - {reduced}");
}

/// Print a confusion matrix and the scores derived from it.
fn print_confusion_matrix(result: &malware_modeler::model::ConfusionMatrix) {
    println!("{result}");
    println!("Accuracy: {:.2}", result.accuracy());
    println!("Precision: {:.2}", result.precision());
    println!("Recall: {:.2}", result.recall());
    println!("F1: {:.2}", result.f1());
    println!("Auc: {:.2}", result.auc());
}

/// Print a confusion matrix and the scores derived from it.
fn print_performance_stats(result: &malware_modeler::model::PerformanceStats) {
    println!("{result}");
    println!("Accuracy: {:.2}", result.accuracy());
    println!("Precision: {:.2}", result.precision());
    println!("Recall: {:.2}", result.recall());
    println!("F1: {:.2}", result.f1());
    println!("Auc: {:.2}", result.auc);
}

/// Evaluate a dataset against a model
#[derive(Parser)]
struct Evaluate {
    /// Path to the dataset
    #[arg(short, long, value_hint = ValueHint::FilePath)]
    dataset: PathBuf,

    /// Path to the model
    #[arg(short, long, value_hint = ValueHint::FilePath)]
    model: PathBuf,

    /// If the model file should be updated to reflect evaluation performance of this test dataset
    #[arg(long, default_value_t = false)]
    update_model: bool,
}

impl Evaluate {
    fn execute(&self) -> Result<ExitCode> {
        let dataset = malware_modeler::dataset::Dataset::load(&self.dataset)?;
        let mut model = malware_modeler::model::LogisticRegression::load(&self.model)?;
        let result = model.evaluate_dataset(&dataset)?;
        print_confusion_matrix(&result);

        if self.update_model {
            model.test_performance = Some(result.into());
            model.save(&self.model)?;
        }

        Ok(ExitCode::SUCCESS)
    }
}

#[derive(Parser)]
struct ModelInfo {
    /// Path to the model
    #[arg(short, long, value_hint = ValueHint::FilePath)]
    model: PathBuf,

    /// Extract n-grams, useful for when a new dataset might be used and the model
    /// features were reduced
    #[arg(short = 'n', long, value_hint = ValueHint::FilePath)]
    extract_ngrams: Option<PathBuf>,

    /// Evaluate a file or directory of files
    #[arg(short, long, value_hint = ValueHint::AnyPath)]
    eval: Option<PathBuf>,

    /// Write the model to a new format
    #[arg(short = 'o', long, value_hint = ValueHint::FilePath)]
    output: Option<PathBuf>,
}

impl ModelInfo {
    fn execute(&self) -> Result<ExitCode> {
        let model = malware_modeler::model::LogisticRegression::load(&self.model)?;
        println!(
            "This model is for {} files and has {} {}-grams",
            model.file_type,
            model.weights.len(),
            model.n
        );
        println!("Original number of features: {}", model.original_ngrams);
        println!("Stride used for n-gram discovery: {}", model.s);
        println!("Learning rate: {}", model.learning_rate);
        println!("L1: {}", model.l1);
        println!("L2: {}", model.l2);
        println!("Trained on: {}", model.created);

        println!("\nTraining performance:");
        print_performance_stats(&model.train_performance);

        if let Some(eval_performance) = &model.test_performance {
            println!("\nEvaluation performance:");
            print_performance_stats(eval_performance);
        }

        if let Some(extract_ngrams) = &self.extract_ngrams {
            let features = model
                .features
                .keys()
                .map(hex::encode)
                .collect::<Vec<String>>()
                .join("\n");
            let mut file = File::create(extract_ngrams)?;
            file.write_all(features.as_bytes())?;
            file.write_all(b"\n")?;
            file.sync_all()?;
        }

        if let Some(eval) = &self.eval {
            if eval.is_file() {
                let (label, prediction, features) = model.evaluate_file(eval)?;
                println!(
                    "{} is predicted to be {label} (raw: {prediction}) and had {features} of {} features",
                    eval.display(),
                    model.features.len()
                );
            } else if eval.is_dir() {
                println!("Path, PredictionLabel, PredictionRaw, FoundFeatures/AvailableFeatures");
                for entry in WalkDir::new(eval)
                    .max_depth(malware_modeler::MAX_RECURSION_DEPTH)
                    .follow_links(true)
                    .into_iter()
                    .flatten()
                {
                    if entry.file_type().is_file() {
                        let (label, prediction, features) = model.evaluate_file(entry.path())?;
                        println!(
                            "{}, {label}, {prediction}, {features}/{}",
                            entry.path().display(),
                            model.features.len()
                        );
                    }
                }
            } else {
                eprintln!("{} is not a file or directory", eval.display());
            }
        }

        if let Some(output) = &self.output {
            ensure!(
                !output.exists(),
                "Refusing to overwrite existing model file {}",
                output.display()
            );

            let Some(new_ext) = output.extension().and_then(|ext| ext.to_str()) else {
                bail!("Output file {} has no extension", output.display());
            };

            let old_ext = self
                .model
                .extension()
                .and_then(|ext| ext.to_str())
                .unwrap_or("");

            if new_ext == old_ext {
                println!(
                    "Output file {} has the same extension as the loaded file, nothing to do",
                    output.display()
                );
            } else {
                model.save(output)?;
            }
        }

        Ok(ExitCode::SUCCESS)
    }
}

/// Show type information or sort files by type with symbolic links and SHA-256 hashes.
#[derive(Parser)]
struct Types {
    #[arg(value_hint = ValueHint::AnyPath)]
    path: PathBuf,

    /// Optionally create symbolic links based on file type to separate types for further actions.
    #[arg(value_hint = ValueHint::DirPath)]
    destination: Option<PathBuf>,

    /// Specify depth for optional type sorting.
    #[arg(long, default_value_t = 3)]
    depth: u8,
}

impl Types {
    pub fn execute(&self) -> Result<ExitCode> {
        if self.path.is_file() {
            let contents = std::fs::read(&self.path)?;
            let ftype = malware_modeler::sorting::FileTypeUnion::from_bytes(&contents);
            println!("{ftype}");
        } else if self.path.is_dir() && self.destination.is_none() {
            for entry in WalkDir::new(&self.path)
                .max_depth(malware_modeler::MAX_RECURSION_DEPTH)
                .follow_links(true)
                .into_iter()
                .flatten()
            {
                if entry.file_type().is_file() {
                    let contents = std::fs::read(entry.path())?;
                    let ftype = malware_modeler::sorting::FileTypeUnion::from_bytes(&contents);
                    println!("{}: {ftype}", entry.path().display());
                }
            }
        } else if self.path.is_dir()
            && let Some(dest) = &self.destination
        {
            let destination = dest.to_owned();

            if destination.is_file() {
                eprintln!("Destination must be a directory, not a file");
                return Ok(ExitCode::FAILURE);
            }

            let result =
                malware_modeler::sorting::file_sorting(&self.path, &destination, self.depth)?;
            println!(
                "Countered {} files, {} of which were duplicates.",
                result.total_files, result.files_removed
            );
            if result.errors > 0 {
                eprintln!("Encountered {} errors while sorting files.", result.errors);
            }
        }
        Ok(ExitCode::SUCCESS)
    }
}

/// Check similarity between files using LZJD
#[derive(Parser, Debug, Clone, PartialEq)]
struct Similarity {
    /// If a file, show the LZJD hash
    one: PathBuf,

    /// Optionally a file if comparing two files
    two: Option<PathBuf>,

    /// Threshold when reporting files too similar
    #[arg(long, default_value_t = 0.8)]
    threshold: f32,

    /// Delete a file which is too similar
    #[arg(long, default_value_t = false)]
    delete_file_if_too_similar_yes_i_really_mean_it: bool,
}

impl Similarity {
    pub fn execute(&self) -> Result<ExitCode> {
        if self.one.is_file() {
            if let Some(two) = &self.two {
                if two.is_file() {
                    let sim = malware_modeler::similarity::lzjd_compare_paths(&self.one, two)?;
                    println!("{sim:.4}");
                }
            } else {
                let lzjd = malware_modeler::similarity::lzjd_from_path(&self.one)?;
                println!("{lzjd}");
            }
        } else {
            if self.two.is_some() {
                bail!("Similarity does not a directory argument with another path");
            }

            let similarity_check = malware_modeler::similarity::Similarity {
                path: &self.one,
                threshold: self.threshold,
            };

            let similar_count = similarity_check.find(|a, b, sim| {
                eprintln!("{} & {} too similar: {sim}", a.display(), b.display());
                if self.delete_file_if_too_similar_yes_i_really_mean_it
                    && std::fs::exists(a).unwrap_or_default()
                    && let Err(e) = std::fs::remove_file(a)
                {
                    eprintln!("Failed to remove {}: {e}", a.display());
                }
            })?;
            println!("Total similar file pairs: {similar_count}");
        }

        Ok(ExitCode::SUCCESS)
    }
}

/// Unzip files from a Zip archive by the type, if the type is known
/// Made with [VirusShare](https://virusshare.com) in mind.
#[derive(Parser, Debug, Clone, PartialEq)]
struct SelectiveUnzip {
    /// Path to the Zip archive
    #[arg(value_hint = ValueHint::FilePath)]
    source: PathBuf,

    /// Destination for the extracted files
    #[arg(value_hint = ValueHint::DirPath)]
    destination: PathBuf,

    /// Password if the Zip archive is encrypted.
    #[arg(short, long)]
    password: Option<String>,

    /// Specify depth for optional type sorting.
    #[arg(long, default_value_t = 3)]
    depth: u8,

    /// The specific file type which should be kept
    #[arg(short = 't', long = "type", value_parser = malware_modeler::sorting::parse_file_type_union)]
    file_type: Option<malware_modeler::sorting::FileTypeUnion>,

    /// Specify the string which should be checked against libmagic, also known as the `file` command.
    /// Ideally should not be used with `-t`, `--type`.
    #[cfg(feature = "libmagic")]
    #[arg(short = 'm', long = "magic")]
    magic: Option<String>,

    /// If unknown files should be kept when keeping all known types
    #[arg(long, default_value_t = false)]
    keep_unknowns: bool,
}

impl SelectiveUnzip {
    pub fn execute(self) -> Result<ExitCode> {
        let extracted_count = malware_modeler::unzip::unzip_files_by_type(
            self.source,
            self.destination,
            self.password.as_ref(),
            self.depth,
            self.file_type,
            #[cfg(feature = "libmagic")]
            self.magic.as_deref(),
            self.keep_unknowns,
        )?;

        println!("Extracted {extracted_count} files");
        Ok(ExitCode::SUCCESS)
    }
}

/// Split a collection of files into train/test/validate using symbolic links
#[derive(Parser, Debug, Clone, PartialEq)]
struct Split {
    /// Path to source malware
    #[arg(long, value_hint = ValueHint::DirPath)]
    malware: PathBuf,

    /// Path to source goodware
    #[arg(long, value_hint = ValueHint::DirPath)]
    goodware: PathBuf,

    /// Destination for malware for training
    #[arg(long, value_hint = ValueHint::DirPath)]
    training_malware: PathBuf,

    /// Destination for malware for testing
    #[arg(long, value_hint = ValueHint::DirPath)]
    testing_malware: PathBuf,

    /// Destination for goodware for training
    #[arg(long, value_hint = ValueHint::DirPath)]
    training_goodware: PathBuf,

    /// Destination for goodware for testing
    #[arg(long, value_hint = ValueHint::DirPath)]
    testing_goodware: PathBuf,

    /// Train-test ratio
    #[arg(long, default_value_t = 0.8)]
    training_ratio: f32,

    /// Destination for validation malware
    #[arg(long, value_hint = ValueHint::DirPath)]
    validation_malware: Option<PathBuf>,

    /// Destination for validation goodware
    #[arg(long, value_hint = ValueHint::DirPath)]
    validation_goodware: Option<PathBuf>,

    /// Train-validation ratio, should be 0.1 or less
    #[arg(long)]
    validation_ratio: Option<f32>,
}

impl Split {
    pub fn execute(self) -> Result<ExitCode> {
        ensure!(
            self.training_ratio > 0.0,
            "Train/test split ratio cannot be negative"
        );
        if self.validation_malware.is_some() != self.validation_goodware.is_some()
            || self.validation_ratio.is_some() != self.validation_malware.is_some()
        {
            bail!("All validation parameters must be provided or none are provided");
        }

        let validation = if let Some(benign) = self.validation_goodware
            && let Some(malicious) = self.validation_malware
            && let Some(split) = self.validation_ratio
        {
            ensure!(split > 0.0, "Validation ratio cannot be negative");
            ensure!(
                split + self.training_ratio < 0.0,
                "Training and split ratios must have a sum less than 1"
            );
            Some(malware_modeler::split::ValidationDirectoriesConfig {
                benign,
                malicious,
                split,
            })
        } else {
            None
        };

        let split_summary = malware_modeler::split::split(
            self.goodware,
            self.malware,
            self.training_goodware,
            self.training_malware,
            self.testing_goodware,
            self.testing_malware,
            self.training_ratio,
            validation.as_ref(),
        )?;
        println!("{split_summary}");

        Ok(ExitCode::SUCCESS)
    }
}

/// What's inside that Zip file??
#[derive(Parser, Debug, Clone, PartialEq)]
struct ZipSummary {
    /// Path to the Zip archive
    #[arg(value_hint = ValueHint::FilePath)]
    source: PathBuf,

    /// Password if the Zip archive is encrypted.
    #[arg(short, long)]
    password: Option<String>,

    /// If unknowns are encountered, how many leading bytes should be captured to display?
    #[arg(short, long, default_value_t = 0)]
    unknown_magic: usize,

    /// If unknowns are encountered, each has to have this minimum occurrence to be displayed.
    #[arg(long, default_value_t = 2)]
    unknown_minimum: usize,
}

impl ZipSummary {
    pub fn execute(self) -> Result<ExitCode> {
        const WIDTH: usize = 14;

        let zip_summary = malware_modeler::unzip::zip_file_type_counts(
            self.source,
            self.password.as_ref(),
            self.unknown_magic,
        )?;

        println!("{0:<WIDTH$} {1:<WIDTH$}", "Type", "Count");
        let mut ordered_summary: Vec<_> = zip_summary.file_type_counts.into_iter().collect();
        ordered_summary.sort_by_key(|b| std::cmp::Reverse(b.1));
        for (ftype, count) in ordered_summary {
            println!("{:<WIDTH$} {count:<WIDTH$}", format!("{ftype}"));
        }

        println!("{:^WIDTH$} {:<WIDTH$}", "Total", zip_summary.total_files);

        if !zip_summary.unknown_magic_counts.is_empty() {
            #[cfg(feature = "libmagic")]
            println!("\n{0:<WIDTH$} {1:<WIDTH$} Magic", "Unknown Header", "Count");
            #[cfg(not(feature = "libmagic"))]
            println!("\n{0:<WIDTH$} {1:<WIDTH$}", "Unknown Header", "Count");

            let mut ordered_summary: Vec<_> =
                zip_summary.unknown_magic_counts.into_iter().collect();
            #[allow(clippy::unnecessary_sort_by)]
            ordered_summary.sort_by(|a, b| b.1.cmp(&a.1));

            #[cfg(feature = "libmagic")]
            for (unknown_bytes, (count, magic)) in ordered_summary {
                if count >= self.unknown_minimum {
                    println!(
                        "{:<WIDTH$} {count:<WIDTH$} {magic}",
                        hex::encode(unknown_bytes)
                    );
                }
            }

            #[cfg(not(feature = "libmagic"))]
            for (unknown_bytes, count) in ordered_summary {
                if count >= self.unknown_minimum {
                    println!("{:<WIDTH$} {count:<WIDTH$}", hex::encode(unknown_bytes));
                }
            }
        }

        Ok(ExitCode::SUCCESS)
    }
}

/// How to generate shell completions.
/// Instructions based on [Clap](https://github.com/clap-rs/clap/blob/master/clap_complete/examples/completion-derive.rs).
///
/// Usage for zsh:
/// ```console
/// $ cargo run -- generate zsh > /usr/local/share/zsh/site-functions/_completion_derive
/// $ compinit
/// $ ./target/debug/malware-modeler <TAB>
/// ```
///
/// Usage for Fish:
/// ```console
/// $ cargo run -- generate fish > completion_derive.fish
/// $ . ./completion_derive.fish
/// $ ./target/debug/malware-modeler <TAB>
/// ```
///
/// Usage for Bash:
/// ```console
/// $ cargo run -- generate bash > completion_derive.bash
/// $ source completion_derive.bash
/// $ ./target/debug/malware-modeler <TAB>
/// ```
#[derive(Parser, Debug, Clone, PartialEq)]
pub struct Generator {
    /// Shell for which to create the completion script
    #[arg(value_enum)]
    shell: Shell,
}

impl Generator {
    #[must_use]
    pub fn execute(&self) -> ExitCode {
        let mut cmd = Args::command();
        self.print_completions(&mut cmd);
        ExitCode::SUCCESS
    }

    fn print_completions(&self, cmd: &mut Command) {
        generate(
            self.shell,
            cmd,
            cmd.get_name().to_string(),
            &mut std::io::stdout(),
        );
    }
}

fn main() -> Result<ExitCode> {
    let args = Args::parse();
    rayon::ThreadPoolBuilder::new()
        .num_threads(args.threads)
        .build_global()?;

    let ret = match args.cmd {
        Actions::Ngram(ngram) => ngram.execute(),
        Actions::Dataset(dataset) => dataset.execute(),
        Actions::DatasetConvert(dataset) => dataset.execute(),
        Actions::DatasetInfo(dataset) => dataset.execute(),
        Actions::DatasetSplit(split) => split.execute(),
        Actions::Train(training) => training.execute(),
        Actions::Evaluate(evaluate) => evaluate.execute(),
        Actions::Model(model) => model.execute(),
        Actions::Types(types) => types.execute(),
        Actions::Similarity(sim) => sim.execute(),
        Actions::SelectiveUnzip(unzip) => unzip.execute(),
        Actions::Split(split) => split.execute(),
        Actions::ZipSummary(summary) => summary.execute(),
        Actions::Generate(generator) => Ok(generator.execute()),
    };

    if let Some(mem) = app_memory_usage_fetcher::get_memory_usage_string() {
        println!("Memory used: {mem}");
    }

    ret
}

#[test]
fn verify_cli() {
    use clap::CommandFactory;

    Args::command().debug_assert();
}