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

//! A fast hasher for n-gram keys.
//!
//! Every byte of every sample passes through a hash: once per window to find the n-grams,
//! and once per window again to featurize against them. The standard library's
//! [`std::hash::DefaultHasher`] is SipHash, chosen to resist collision attacks on
//! attacker-supplied keys. N-gram keys are eight bytes of a file being analysed, not map keys
//! an attacker can pick to degrade a lookup, and SipHash's setup cost dominates at that size:
//! measured over 64 MiB of windows it costs 6.2 ns each against 0.3 ns for the hasher here.
//!
//! This is the rustc-hash (FxHash) algorithm — a rotate, xor and multiply per eight bytes.
//! It is written out rather than pulled in as a dependency because it is twenty lines.

use std::hash::{BuildHasherDefault, Hasher};

/// Multiplier from rustc-hash, chosen to spread the input across the whole word.
const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;

/// Fast, non-cryptographic hasher for short byte keys.
///
/// Not resistant to deliberate collisions, so do not use it for keys an untrusted party
/// chooses.
#[derive(Default, Clone, Copy)]
pub struct FxHasher {
    /// Running hash state
    hash: u64,
}

impl FxHasher {
    /// Fold one word into the state.
    #[inline]
    fn add(&mut self, word: u64) {
        self.hash = (self.hash.rotate_left(5) ^ word).wrapping_mul(SEED);
    }
}

impl Hasher for FxHasher {
    #[inline]
    fn finish(&self) -> u64 {
        // Finalization is not optional here. Multiply-based mixing propagates entropy towards
        // the high bits — bit i of a product depends only on multiplicand bits 0..=i — while
        // `HashMap` takes its bucket index from the *low* bits. Returning the raw state means
        // keys differing only in their high-order bytes share a bucket and the map degrades to
        // a linear scan: 4096 hex-decoded n-grams, which are big-endian and so vary in their
        // high bytes, produced exactly one distinct bucket index.
        //
        // This is MurmurHash3's fmix64. Two rounds are needed; one fold-and-multiply still
        // leaves the bottom bits constant for such keys.
        let mut hash = self.hash;
        hash ^= hash >> 33;
        hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
        hash ^= hash >> 33;
        hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
        hash ^= hash >> 33;
        hash
    }

    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        let mut rest = bytes;

        while let Some((word, tail)) = rest.split_at_checked(8) {
            // The slice is exactly eight bytes, so the conversion cannot fail.
            if let Ok(word) = <[u8; 8]>::try_from(word) {
                self.add(u64::from_le_bytes(word));
            }
            rest = tail;
        }

        if !rest.is_empty() {
            let mut last = [0u8; 8];
            last[..rest.len()].copy_from_slice(rest);
            self.add(u64::from_le_bytes(last));
        }
    }

    #[inline]
    fn write_u8(&mut self, value: u8) {
        self.add(u64::from(value));
    }

    #[inline]
    fn write_usize(&mut self, value: usize) {
        self.add(value as u64);
    }
}

/// [`std::hash::BuildHasher`] for [`FxHasher`], for use as a `HashMap`'s third type parameter.
pub type FxBuildHasher = BuildHasherDefault<FxHasher>;

/// A `HashMap` keyed with [`FxHasher`].
pub type FxHashMap<K, V> = std::collections::HashMap<K, V, FxBuildHasher>;

/// Hash a byte slice in one call.
#[inline]
#[must_use]
pub fn hash_bytes(bytes: &[u8]) -> u64 {
    let mut hasher = FxHasher::default();
    hasher.write(bytes);
    hasher.finish()
}

#[cfg(test)]
mod tests {
    use super::{FxHashMap, hash_bytes};

    #[test]
    fn distinct_inputs_hash_differently() {
        // Not a guarantee in general, but these must not collide for the hasher to be usable.
        let samples: Vec<[u8; 8]> = (0u64..4096).map(u64::to_le_bytes).collect();
        let mut hashes = samples.iter().map(|s| hash_bytes(s)).collect::<Vec<_>>();
        hashes.sort_unstable();
        let before = hashes.len();
        hashes.dedup();
        assert_eq!(
            hashes.len(),
            before,
            "collisions among 4096 sequential keys"
        );
    }

    #[test]
    fn hashing_is_stable_and_length_sensitive() {
        assert_eq!(hash_bytes(b"12345678"), hash_bytes(b"12345678"));
        assert_ne!(hash_bytes(b"12345678"), hash_bytes(b"12345679"));

        // Lengths that don't land on a word boundary must still be handled.
        assert_ne!(hash_bytes(b"1234"), hash_bytes(b"12345"));
        assert_ne!(hash_bytes(b""), hash_bytes(b"1"));
        assert_eq!(hash_bytes(b"123456789"), hash_bytes(b"123456789"));
    }

    /// The property `HashMap` actually depends on: bucket indices come from the low bits, so
    /// keys differing only in their high-order bytes must still spread.
    ///
    /// Without finalization this produced a single distinct value, making every map keyed on
    /// hex-decoded n-grams a linear scan.
    #[test]
    fn low_bits_spread_for_high_order_variation() {
        const KEYS: u64 = 4096;
        const MASK: u64 = 0xFFF;

        // Big-endian sequential values are what `hex::decode` of an n-gram list produces: the
        // varying bytes sit at the end, so a little-endian read puts them in the high bits.
        let mut buckets = (0..KEYS)
            .map(|key| hash_bytes(&key.to_be_bytes()) & MASK)
            .collect::<Vec<_>>();
        buckets.sort_unstable();
        buckets.dedup();

        // Random assignment of 4096 keys over 4096 buckets fills about 1 - 1/e of them.
        assert!(
            buckets.len() as u64 > KEYS / 2,
            "only {} distinct bucket indices for {KEYS} keys",
            buckets.len()
        );
    }

    /// Clustering shows up as a map that takes minutes rather than milliseconds to fill.
    #[test]
    fn map_of_high_order_keys_is_not_quadratic() {
        const KEYS: u64 = 200_000;

        let start = std::time::Instant::now();
        let mut map: FxHashMap<Vec<u8>, u64> = FxHashMap::default();
        for key in 0..KEYS {
            map.insert(key.to_be_bytes().to_vec(), key);
        }
        for key in 0..KEYS {
            assert_eq!(map.get(key.to_be_bytes().as_slice()), Some(&key));
        }
        let elapsed = start.elapsed();

        assert_eq!(map.len() as u64, KEYS);
        assert!(
            elapsed.as_secs() < 20,
            "filling and probing {KEYS} keys took {elapsed:?}, which suggests clustering"
        );
    }

    #[test]
    fn works_as_a_map_hasher() {
        let mut map: FxHashMap<Vec<u8>, usize> = FxHashMap::default();
        for index in 0..1000usize {
            map.insert(index.to_le_bytes().to_vec(), index);
        }

        assert_eq!(map.len(), 1000);
        for index in 0..1000usize {
            assert_eq!(map.get(index.to_le_bytes().as_slice()), Some(&index));
        }
        assert_eq!(map.get(b"missing".as_slice()), None);
    }
}