Skip to main content

linprov_common/
lib.rs

1//! Types shared between the eBPF program (`linprov-ebpf`) and the userspace
2//! daemon (`linprov`). Everything here is `repr(C)` and Pod-friendly so it
3//! survives a round-trip through a ring buffer and a kernel xattr.
4//!
5//! The crate compiles `no_std` by default (for the BPF target). Enable the
6//! `user` feature in userspace to pull in `bytemuck::Pod` / `Zeroable`
7//! derives on the wire types.
8//!
9//! Wire shapes at a glance:
10//!
11//! - [`OriginRecord`] is what the daemon stores in the xattr and in the BPF
12//!   `INODE_MARKS` map. BPF writes most of it in `file_open`; userspace
13//!   augments `creator_path` from `/proc/$pid/exe`.
14//! - [`Event`] is the ringbuf record streamed from BPF to userspace.
15//! - [`AllowRule`] is one allowlist rule, packed into the BPF
16//!   `ALLOW_RULES` array. String dims are stored as [`fnv_hash`] values
17//!   so the BPF side can compare without carrying full byte arrays.
18//!
19//! ```
20//! use linprov_common::{fnv_hash, dim};
21//!
22//! // Both sides hash strings the same way; same input → same u64.
23//! assert_eq!(fnv_hash("/usr/bin/curl"), fnv_hash("/usr/bin/curl"));
24//! assert_ne!(fnv_hash("/usr/bin/curl"), fnv_hash("/usr/bin/wget"));
25//!
26//! // Dimension bits are independent flags on AllowRule::flags.
27//! let two_dim = dim::CREATOR_UID | dim::CREATOR_COMM;
28//! assert_eq!(two_dim.count_ones(), 2);
29//! ```
30
31#![cfg_attr(not(feature = "user"), no_std)]
32
33pub const COMM_LEN: usize = 16;
34
35/// Live exec/target path buffer size: the ringbuf [`Event`] filename
36/// and the per-CPU scratch the target-dim walks scan. Sized to Linux
37/// `PATH_MAX` so `target_filename` / `target_folder` match the full
38/// execution path at any depth and any length. These buffers are
39/// transient (per-CPU scratch + ringbuf), never persisted, so they
40/// aren't bound by the xattr block-size limit that caps stored data.
41pub const EXEC_PATH_LEN: usize = 4096;
42
43/// Max bytes the BPF path walks inspect. Equal to [`EXEC_PATH_LEN`]:
44/// the walk body is a `bpf_loop` callback the verifier inspects once,
45/// so this is bounded only by the buffer, not the instruction budget.
46pub const PATH_HASH_SCAN_LEN: usize = EXEC_PATH_LEN;
47
48/// Number of landing-folder ancestor hashes stored per record, for
49/// nested `landing_folder` matching. The walk records the hash of each
50/// `/`-terminated prefix of the landing path (shallow → deep) into a
51/// `[u64; MAX_FOLDER_ANCESTORS]`; a rule matches if its folder hash
52/// equals any of them, so `landing_folder=/home/user/` matches a file
53/// that landed in `/home/user/Downloads/sub/`. Bounds nesting *depth*
54/// (path length is still unbounded — these are hashes). Must be a power
55/// of two: the in-kernel walk masks the index (`& (N-1)`) to keep the
56/// array write provably in-bounds without a panic branch. Real landing
57/// paths sit well under this, so the mask never actually wraps.
58///
59/// Capped at 32 by the BPF 512-byte stack limit: the `file_open` walk
60/// holds this array by value in its `bpf_loop` context (`32 × 8 = 256`
61/// bytes, plus the other context fields). 64 would overflow the stack
62/// frame — it'd need the array in a per-CPU map instead, not worth it
63/// when 32 ancestor levels already exceeds any real landing path.
64pub const MAX_FOLDER_ANCESTORS: usize = 32;
65
66// FNV-1a-64 constants. Used by both sides to hash strings.
67pub const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
68pub const FNV_PRIME: u64 = 0x100_0000_01b3;
69
70/// Hash a string with FNV-1a-64. Byte-by-byte, no trailing NUL, no
71/// padding — identical on the BPF and userspace sides.
72///
73/// Both sides MUST compute the same hash for the same input; the FNV
74/// constants ([`FNV_OFFSET`], [`FNV_PRIME`]) are fixed for that reason.
75///
76/// ```
77/// use linprov_common::fnv_hash;
78/// // FNV-1a of the empty string is the offset basis.
79/// assert_eq!(fnv_hash(""), 0xcbf2_9ce4_8422_2325);
80/// // Distinct inputs hash distinctly.
81/// assert_ne!(fnv_hash("/tmp/"), fnv_hash("/etc/"));
82/// ```
83pub fn fnv_hash(s: &str) -> u64 {
84    fnv_hash_bytes(s.as_bytes())
85}
86
87/// Same as [`fnv_hash`], but takes a byte slice. Useful when the source
88/// isn't UTF-8 (e.g., a `[u8; EXEC_PATH_LEN]` filename buffer read out
89/// of a ringbuf event).
90pub fn fnv_hash_bytes(bytes: &[u8]) -> u64 {
91    let mut h = FNV_OFFSET;
92    for &b in bytes {
93        h ^= b as u64;
94        h = h.wrapping_mul(FNV_PRIME);
95    }
96    h
97}
98
99// ----- Allowlist rule. One per line in the allowlist file; each rule
100// is a conjunction of (dim, value) conditions. Rules OR together.
101
102/// `flags` bits on [`AllowRule`]. Bits 0–7 are the dims a rule requires.
103/// Bits 8+ are *modifiers* on a dim already set.
104pub mod dim {
105    pub const TARGET_FILENAME: u32 = 1 << 0;
106    pub const TARGET_FOLDER: u32 = 1 << 1;
107    pub const LANDING_FILENAME: u32 = 1 << 2;
108    pub const LANDING_FOLDER: u32 = 1 << 3;
109    pub const CREATOR_PROCESS: u32 = 1 << 4;
110    pub const CREATOR_COMM: u32 = 1 << 5;
111    pub const CREATOR_UID: u32 = 1 << 6;
112    pub const EXECUTION_UID: u32 = 1 << 7;
113
114    /// Modifier on `TARGET_FOLDER`: match the folder **or any descendant**
115    /// (`target_folder=/opt/app/*`) instead of only files directly in it
116    /// (`target_folder=/opt/app/`). Recursive = the rule folder is any
117    /// `/`-prefix of the live exec path; exact = the rule folder is the
118    /// executed file's immediate parent.
119    pub const TARGET_FOLDER_RECURSIVE: u32 = 1 << 8;
120    /// Modifier on `LANDING_FOLDER`, same meaning for the landing path.
121    /// Recursive = any of the record's stored ancestor hashes; exact =
122    /// the immediate-parent hash.
123    pub const LANDING_FOLDER_RECURSIVE: u32 = 1 << 9;
124}
125
126/// Maximum number of allowlist rules carried by the BPF `ALLOW_RULES`
127/// Array map (× 72 bytes ≈ 590 KiB at this size).
128///
129/// The per-rule scan runs inside a single `bpf_loop` callback
130/// (`allow_step`), so the verifier inspects the rule body **once** instead
131/// of unrolling it — this value costs map memory and at-most-N runtime
132/// iterations per execve (N = the actual rule count, not this ceiling),
133/// but is O(1) to the verifier and to daemon load time. The earlier
134/// *unrolled* loop topped out below 64 rules against the 1M-instruction
135/// budget; this is 256× the old 32-rule limit. An over-capacity allowlist
136/// degrades gracefully (the daemon loads the first `MAX_RULES` and warns —
137/// see `check_capacity`), so it never crash-loops on a file that outgrew
138/// the ceiling.
139pub const MAX_RULES: usize = 8192;
140
141/// One allowlist rule. Set bits in `flags` mark required dims; the
142/// corresponding fields below are then compared against the record /
143/// execve context at enforce time. Cleared bits → field ignored.
144///
145/// Strings are stored as FNV-1a-64 hashes (computed identically in
146/// userspace and BPF). Collision probability for distinct strings under
147/// FNV-64 is negligible at any realistic allowlist size.
148#[repr(C)]
149#[derive(Copy, Clone)]
150#[cfg_attr(feature = "user", derive(bytemuck::Pod, bytemuck::Zeroable))]
151pub struct AllowRule {
152    pub flags: u32,
153    pub creator_uid: u32,
154    pub execution_uid: u32,
155    pub _pad: u32,
156    pub creator_comm: [u8; COMM_LEN],
157    pub target_filename_hash: u64,
158    pub target_folder_hash: u64,
159    pub landing_filename_hash: u64,
160    pub landing_folder_hash: u64,
161    pub creator_process_hash: u64,
162}
163
164pub const XATTR_NAME: &str = "security.bpf.linprov.origin";
165
166pub const EVENT_KIND_NETWORK_FILE_OPEN: u32 = 1;
167pub const EVENT_KIND_EXECVE: u32 = 2;
168/// A file written by a process that had **read** a marked file (taint
169/// propagation — e.g. `tar`/`unzip` extracting a marked archive, or `cp`
170/// of a marked file). The carried `origin` is inherited from the source
171/// file's record; userspace persists the xattr without re-resolving the
172/// creator (the inherited creator identity is kept verbatim).
173pub const EVENT_KIND_DERIVED_FILE_OPEN: u32 = 3;
174/// A marked file opened for **read** by a known script interpreter
175/// (bash/python/…) — i.e. `python foo.py` / `bash foo.sh` / `. foo.sh`,
176/// where the kernel execve's the unmarked interpreter and the script
177/// itself never reaches `bprm_check_security`. The eBPF `file_open` read
178/// branch runs the same allowlist check used at execve against the
179/// script's path; in enforce mode `status` is the LSM verdict (`-1`
180/// blocked). The `filename` carries the script's path and `comm` the
181/// script's basename, so the script — not the interpreter — is the unit
182/// surfaced in logs and soak. Matches `EVENT_KIND_EXECVE` handling.
183pub const EVENT_KIND_SCRIPT_EXEC: u32 = 4;
184
185/// Runtime mode communicated to the eBPF program via the CONFIG map.
186pub const MODE_OBSERVE: u32 = 0;
187pub const MODE_SOAK: u32 = 1; // eBPF behaves like OBSERVE; userspace records paths
188pub const MODE_ENFORCE: u32 = 2;
189
190/// Current schema version of [`OriginRecord`]. Records carrying a different
191/// version are treated as unmarked.
192///
193/// v4 made the record fully hash-based: the variable-length path fields
194/// (`creator_path`, the landing folder, the landing basename) became
195/// `u64` FNV hashes instead of fixed buffers. This lifts the path-length
196/// ceiling (a hash is the same 8 bytes whether the path is 12 or 4096
197/// bytes) and shrinks the record to 64 bytes, well under the xattr
198/// block limit. Human-readable resolution of those hashes lives in the
199/// plaintext audit db (see the `hashdb` userspace module), not in the
200/// record. v3 records (which embedded path strings) are treated as
201/// unmarked and get re-marked on next open.
202pub const ORIGIN_VERSION: u32 = 4;
203
204/// Provenance record. Carried in the `security.bpf.linprov.origin` xattr
205/// and in the INODE_MARKS storage map. Fixed 64 bytes — every
206/// variable-length field is an FNV-1a-64 hash, so the record never
207/// grows with path length and always fits a single xattr block.
208///
209/// Filled in stages:
210///   * BPF `file_open` sets `version`, `pid`, `ts_boot_ns`, `comm`,
211///     `creator_uid`, and the two landing hashes (`landing_folder_hash`,
212///     `landing_basename_hash`), computed in one pass over the landing
213///     path. `creator_path_hash` is left 0 — BPF can't cheaply resolve
214///     the creator's exe path here.
215///   * Userspace, on the corresponding ringbuf event, reads
216///     `/proc/$pid/exe`, fills `creator_path_hash`, and overwrites the
217///     xattr with the augmented record. It also records each hash →
218///     path mapping in the plaintext audit db so logs, soak, and the
219///     user's own `grep` can resolve hashes back to paths.
220///
221/// `creator_path_hash == 0` is the "not yet augmented" sentinel:
222/// `bprm_check_security` reads the storage record first and falls
223/// through to the xattr when it sees a zero creator hash. Rules keyed
224/// on `creator_process` won't match an unaugmented record, but other
225/// dims still do.
226#[repr(C)]
227#[derive(Copy, Clone)]
228#[cfg_attr(feature = "user", derive(bytemuck::Pod, bytemuck::Zeroable))]
229pub struct OriginRecord {
230    pub version: u32,
231    pub pid: u32,
232    pub ts_boot_ns: u64,
233    pub comm: [u8; COMM_LEN],
234    pub creator_uid: u32,
235    pub _pad: u32,
236    /// FNV-1a-64 of the creator's full exe path (`/proc/$pid/exe`).
237    /// 0 until userspace augments the record.
238    pub creator_path_hash: u64,
239    /// FNV-1a-64 of the landing file's immediate parent directory,
240    /// including the trailing `/` (matches `normalize_folder`). Always
241    /// the immediate parent regardless of depth — used for exact
242    /// `landing_folder` matching and for soak/log resolution.
243    pub landing_folder_hash: u64,
244    /// FNV-1a-64 of the landing file's basename (final path component,
245    /// no slash).
246    pub landing_basename_hash: u64,
247    /// FNV-1a-64 of each `/`-terminated ancestor of the landing path
248    /// (shallow → deep), up to [`MAX_FOLDER_ANCESTORS`]. Enables nested
249    /// `landing_folder` matching: a rule whose folder hash equals any
250    /// entry matches. Unused slots are 0.
251    pub landing_ancestor_hashes: [u64; MAX_FOLDER_ANCESTORS],
252}
253
254/// Ring-buffer record. Two kinds:
255///   NetworkFileOpen — informational; eBPF just wrote (or tried to write)
256///     the xattr. `status` is the kfunc return code.
257///   Execve — bprm_check fired AND the file already carried the mark.
258///     `origin` is the record we read back; `status` is unused.
259#[repr(C)]
260#[derive(Copy, Clone)]
261#[cfg_attr(feature = "user", derive(bytemuck::Pod, bytemuck::Zeroable))]
262pub struct Event {
263    pub kind: u32,
264    pub pid: u32,
265    pub tgid: u32,
266    pub status: i32,
267    pub comm: [u8; COMM_LEN],
268    pub origin: OriginRecord,
269    /// The live path: landing path for `NetworkFileOpen`, exec/target
270    /// path for `Execve`. Sized to `PATH_MAX`; transient (ringbuf only).
271    pub filename: [u8; EXEC_PATH_LEN],
272}
273
274impl Event {
275    pub const SIZE: usize = core::mem::size_of::<Self>();
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281
282    #[test]
283    fn fnv_known_vectors() {
284        // FNV-1a-64 offset basis for the empty string.
285        assert_eq!(fnv_hash(""), 0xcbf2_9ce4_8422_2325);
286        // Pre-computed reference values from a separate FNV implementation.
287        assert_eq!(fnv_hash("a"), 0xaf63_dc4c_8601_ec8c);
288        assert_eq!(fnv_hash("foobar"), 0x85944171_f73967e8);
289    }
290
291    #[test]
292    fn fnv_string_and_bytes_agree() {
293        let s = "/usr/bin/curl";
294        assert_eq!(fnv_hash(s), fnv_hash_bytes(s.as_bytes()));
295    }
296
297    #[test]
298    fn dim_flags_are_unique() {
299        let all = [
300            dim::TARGET_FILENAME,
301            dim::TARGET_FOLDER,
302            dim::LANDING_FILENAME,
303            dim::LANDING_FOLDER,
304            dim::CREATOR_PROCESS,
305            dim::CREATOR_COMM,
306            dim::CREATOR_UID,
307            dim::EXECUTION_UID,
308        ];
309        let mut acc = 0u32;
310        for d in all {
311            assert_eq!(d.count_ones(), 1, "each dim is one bit");
312            assert_eq!(acc & d, 0, "dim {d:#b} overlaps with prior {acc:#b}");
313            acc |= d;
314        }
315    }
316
317    #[test]
318    fn origin_record_size_is_v4_expected() {
319        // 4 + 4 + 8 + 16 + 4 + 4 + 8 + 8 + 8 + 8*MAX_FOLDER_ANCESTORS
320        let base = 4 + 4 + 8 + 16 + 4 + 4 + 8 + 8 + 8;
321        assert_eq!(
322            core::mem::size_of::<OriginRecord>(),
323            base + 8 * MAX_FOLDER_ANCESTORS
324        );
325    }
326
327    #[test]
328    fn allow_rule_size_has_no_padding() {
329        // 4 + 4 + 4 + 4 + 16 + 8*5 = 72
330        assert_eq!(core::mem::size_of::<AllowRule>(), 72);
331    }
332
333    #[test]
334    fn fnv_constants_match_reference() {
335        // FNV-1a-64 parameters per http://www.isthe.com/chongo/tech/comp/fnv/
336        assert_eq!(FNV_OFFSET, 0xcbf2_9ce4_8422_2325);
337        assert_eq!(FNV_PRIME, 0x100_0000_01b3);
338    }
339}