Skip to main content

malware_modeler/
hash.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! A fast hasher for n-gram keys.
4//!
5//! Every byte of every sample passes through a hash: once per window to find the n-grams,
6//! and once per window again to featurize against them. The standard library's
7//! [`std::hash::DefaultHasher`] is SipHash, chosen to resist collision attacks on
8//! attacker-supplied keys. N-gram keys are eight bytes of a file being analysed, not map keys
9//! an attacker can pick to degrade a lookup, and SipHash's setup cost dominates at that size:
10//! measured over 64 MiB of windows it costs 6.2 ns each against 0.3 ns for the hasher here.
11//!
12//! This is the rustc-hash (FxHash) algorithm — a rotate, xor and multiply per eight bytes.
13//! It is written out rather than pulled in as a dependency because it is twenty lines.
14
15use std::hash::{BuildHasherDefault, Hasher};
16
17/// Multiplier from rustc-hash, chosen to spread the input across the whole word.
18const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
19
20/// Fast, non-cryptographic hasher for short byte keys.
21///
22/// Not resistant to deliberate collisions, so do not use it for keys an untrusted party
23/// chooses.
24#[derive(Default, Clone, Copy)]
25pub struct FxHasher {
26    /// Running hash state
27    hash: u64,
28}
29
30impl FxHasher {
31    /// Fold one word into the state.
32    #[inline]
33    fn add(&mut self, word: u64) {
34        self.hash = (self.hash.rotate_left(5) ^ word).wrapping_mul(SEED);
35    }
36}
37
38impl Hasher for FxHasher {
39    #[inline]
40    fn finish(&self) -> u64 {
41        // Finalization is not optional here. Multiply-based mixing propagates entropy towards
42        // the high bits — bit i of a product depends only on multiplicand bits 0..=i — while
43        // `HashMap` takes its bucket index from the *low* bits. Returning the raw state means
44        // keys differing only in their high-order bytes share a bucket and the map degrades to
45        // a linear scan: 4096 hex-decoded n-grams, which are big-endian and so vary in their
46        // high bytes, produced exactly one distinct bucket index.
47        //
48        // This is MurmurHash3's fmix64. Two rounds are needed; one fold-and-multiply still
49        // leaves the bottom bits constant for such keys.
50        let mut hash = self.hash;
51        hash ^= hash >> 33;
52        hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
53        hash ^= hash >> 33;
54        hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
55        hash ^= hash >> 33;
56        hash
57    }
58
59    #[inline]
60    fn write(&mut self, bytes: &[u8]) {
61        let mut rest = bytes;
62
63        while let Some((word, tail)) = rest.split_at_checked(8) {
64            // The slice is exactly eight bytes, so the conversion cannot fail.
65            if let Ok(word) = <[u8; 8]>::try_from(word) {
66                self.add(u64::from_le_bytes(word));
67            }
68            rest = tail;
69        }
70
71        if !rest.is_empty() {
72            let mut last = [0u8; 8];
73            last[..rest.len()].copy_from_slice(rest);
74            self.add(u64::from_le_bytes(last));
75        }
76    }
77
78    #[inline]
79    fn write_u8(&mut self, value: u8) {
80        self.add(u64::from(value));
81    }
82
83    #[inline]
84    fn write_usize(&mut self, value: usize) {
85        self.add(value as u64);
86    }
87}
88
89/// [`std::hash::BuildHasher`] for [`FxHasher`], for use as a `HashMap`'s third type parameter.
90pub type FxBuildHasher = BuildHasherDefault<FxHasher>;
91
92/// A `HashMap` keyed with [`FxHasher`].
93pub type FxHashMap<K, V> = std::collections::HashMap<K, V, FxBuildHasher>;
94
95/// Hash a byte slice in one call.
96#[inline]
97#[must_use]
98pub fn hash_bytes(bytes: &[u8]) -> u64 {
99    let mut hasher = FxHasher::default();
100    hasher.write(bytes);
101    hasher.finish()
102}
103
104#[cfg(test)]
105mod tests {
106    use super::{FxHashMap, hash_bytes};
107
108    #[test]
109    fn distinct_inputs_hash_differently() {
110        // Not a guarantee in general, but these must not collide for the hasher to be usable.
111        let samples: Vec<[u8; 8]> = (0u64..4096).map(u64::to_le_bytes).collect();
112        let mut hashes = samples.iter().map(|s| hash_bytes(s)).collect::<Vec<_>>();
113        hashes.sort_unstable();
114        let before = hashes.len();
115        hashes.dedup();
116        assert_eq!(
117            hashes.len(),
118            before,
119            "collisions among 4096 sequential keys"
120        );
121    }
122
123    #[test]
124    fn hashing_is_stable_and_length_sensitive() {
125        assert_eq!(hash_bytes(b"12345678"), hash_bytes(b"12345678"));
126        assert_ne!(hash_bytes(b"12345678"), hash_bytes(b"12345679"));
127
128        // Lengths that don't land on a word boundary must still be handled.
129        assert_ne!(hash_bytes(b"1234"), hash_bytes(b"12345"));
130        assert_ne!(hash_bytes(b""), hash_bytes(b"1"));
131        assert_eq!(hash_bytes(b"123456789"), hash_bytes(b"123456789"));
132    }
133
134    /// The property `HashMap` actually depends on: bucket indices come from the low bits, so
135    /// keys differing only in their high-order bytes must still spread.
136    ///
137    /// Without finalization this produced a single distinct value, making every map keyed on
138    /// hex-decoded n-grams a linear scan.
139    #[test]
140    fn low_bits_spread_for_high_order_variation() {
141        const KEYS: u64 = 4096;
142        const MASK: u64 = 0xFFF;
143
144        // Big-endian sequential values are what `hex::decode` of an n-gram list produces: the
145        // varying bytes sit at the end, so a little-endian read puts them in the high bits.
146        let mut buckets = (0..KEYS)
147            .map(|key| hash_bytes(&key.to_be_bytes()) & MASK)
148            .collect::<Vec<_>>();
149        buckets.sort_unstable();
150        buckets.dedup();
151
152        // Random assignment of 4096 keys over 4096 buckets fills about 1 - 1/e of them.
153        assert!(
154            buckets.len() as u64 > KEYS / 2,
155            "only {} distinct bucket indices for {KEYS} keys",
156            buckets.len()
157        );
158    }
159
160    /// Clustering shows up as a map that takes minutes rather than milliseconds to fill.
161    #[test]
162    fn map_of_high_order_keys_is_not_quadratic() {
163        const KEYS: u64 = 200_000;
164
165        let start = std::time::Instant::now();
166        let mut map: FxHashMap<Vec<u8>, u64> = FxHashMap::default();
167        for key in 0..KEYS {
168            map.insert(key.to_be_bytes().to_vec(), key);
169        }
170        for key in 0..KEYS {
171            assert_eq!(map.get(key.to_be_bytes().as_slice()), Some(&key));
172        }
173        let elapsed = start.elapsed();
174
175        assert_eq!(map.len() as u64, KEYS);
176        assert!(
177            elapsed.as_secs() < 20,
178            "filling and probing {KEYS} keys took {elapsed:?}, which suggests clustering"
179        );
180    }
181
182    #[test]
183    fn works_as_a_map_hasher() {
184        let mut map: FxHashMap<Vec<u8>, usize> = FxHashMap::default();
185        for index in 0..1000usize {
186            map.insert(index.to_le_bytes().to_vec(), index);
187        }
188
189        assert_eq!(map.len(), 1000);
190        for index in 0..1000usize {
191            assert_eq!(map.get(index.to_le_bytes().as_slice()), Some(&index));
192        }
193        assert_eq!(map.get(b"missing".as_slice()), None);
194    }
195}