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
// SPDX-License-Identifier: Apache-2.0

use crate::MAX_RECURSION_DEPTH;

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};

use anyhow::{Result, ensure};
use malwaredb_lzjd2::lzjd::LzDigest;
use rayon::prelude::*;
use walkdir::WalkDir;

/// Convenience wrapper for getting LZJD object
///
/// For more information on LZJD, see <https://github.com/edwardraff/LZJD>
///
/// # Errors
///
/// An error occurs if the file can't be read or is empty
#[inline]
pub fn lzjd_from_path<P: AsRef<Path>>(path: P) -> Result<LzDigest> {
    ensure!(path.as_ref().is_file(), "Path must be a file");
    let contents = std::fs::read(path)?;
    ensure!(!contents.is_empty(), "empty file");
    Ok(LzDigest::from(contents.as_slice()))
}

/// Convenience wrapper for getting a LZJD similarity value for two paths
///
/// For more information on LZJD, see <https://github.com/edwardraff/LZJD>
///
/// # Errors
///
/// An error occurs if the file can't be read or is empty
#[inline]
pub fn lzjd_compare_paths<P: AsRef<Path>>(path_a: P, path_b: P) -> Result<f32> {
    let lzjd_a = lzjd_from_path(path_a)?;
    let lzjd_b = lzjd_from_path(path_b)?;
    Ok(lzjd_a.similarity(&lzjd_b))
}

/// Similarity checker
#[derive(Debug, Clone)]
pub struct Similarity<P: AsRef<Path> + Send + Sync> {
    /// Path to check
    pub path: P,

    /// Threshold for when files are considered too similar
    pub threshold: f32,
}

impl<P: AsRef<Path> + Send + Sync> Similarity<P> {
    /// Find similar files in a directory, calling the provided closure for each match with the
    /// similarity score.
    ///
    /// Returns the number of similar file pairs found.
    ///
    /// # Errors
    ///
    /// An error results if a file can't be read
    pub fn find<F>(&self, f: F) -> Result<usize>
    where
        F: Fn(&Path, &Path, f32) + Send + Sync,
    {
        ensure!(
            self.path.as_ref().is_dir(),
            "{} needs to be a directory",
            self.path.as_ref().display()
        );

        // Digest each file once. The previous version built this map and then never read it:
        // the comparison below called `lzjd_compare_paths`, which re-opened and re-digested
        // both files for every pair. That is two file reads per pair, so n^2 reads of the whole
        // corpus instead of n.
        let mut digests: Vec<(PathBuf, LzDigest)> = Vec::new();
        for entry in WalkDir::new(&self.path)
            .max_depth(MAX_RECURSION_DEPTH)
            .follow_links(true)
            .into_iter()
            .flatten()
        {
            if entry.path().is_file() {
                let digest = lzjd_from_path(entry.path())?;
                digests.push((entry.into_path(), digest));
            }
        }

        let similar_count = AtomicUsize::new(0);

        // Each unordered pair is visited exactly once, so there is nothing to remember about
        // which pairs have been reported. The previous version compared every ordered pair and
        // kept a set of two formatted strings per pair to suppress the duplicates, which is
        // two allocations per pair and a set that grows with the square of the corpus.
        digests
            .par_iter()
            .enumerate()
            .for_each(|(index, (path_a, digest_a))| {
                for (path_b, digest_b) in &digests[index + 1..] {
                    let similarity = digest_a.similarity(digest_b);
                    if similarity >= self.threshold {
                        f(path_a, path_b, similarity);
                        similar_count.fetch_add(1, Ordering::Relaxed);
                    }
                }
            });

        Ok(similar_count.into_inner())
    }
}