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 Array map.
127/// Each rule check is ~30 ops + 2 folder lookups; the verifier walks
128/// the full bounded loop, so this caps the per-execve cost.
129pub const MAX_RULES: usize = 32;
130
131/// One allowlist rule. Set bits in `flags` mark required dims; the
132/// corresponding fields below are then compared against the record /
133/// execve context at enforce time. Cleared bits → field ignored.
134///
135/// Strings are stored as FNV-1a-64 hashes (computed identically in
136/// userspace and BPF). Collision probability for distinct strings under
137/// FNV-64 is negligible at any realistic allowlist size.
138#[repr(C)]
139#[derive(Copy, Clone)]
140#[cfg_attr(feature = "user", derive(bytemuck::Pod, bytemuck::Zeroable))]
141pub struct AllowRule {
142 pub flags: u32,
143 pub creator_uid: u32,
144 pub execution_uid: u32,
145 pub _pad: u32,
146 pub creator_comm: [u8; COMM_LEN],
147 pub target_filename_hash: u64,
148 pub target_folder_hash: u64,
149 pub landing_filename_hash: u64,
150 pub landing_folder_hash: u64,
151 pub creator_process_hash: u64,
152}
153
154pub const XATTR_NAME: &str = "security.bpf.linprov.origin";
155
156pub const EVENT_KIND_NETWORK_FILE_OPEN: u32 = 1;
157pub const EVENT_KIND_EXECVE: u32 = 2;
158/// A file written by a process that had **read** a marked file (taint
159/// propagation — e.g. `tar`/`unzip` extracting a marked archive, or `cp`
160/// of a marked file). The carried `origin` is inherited from the source
161/// file's record; userspace persists the xattr without re-resolving the
162/// creator (the inherited creator identity is kept verbatim).
163pub const EVENT_KIND_DERIVED_FILE_OPEN: u32 = 3;
164/// A marked file opened for **read** by a known script interpreter
165/// (bash/python/…) — i.e. `python foo.py` / `bash foo.sh` / `. foo.sh`,
166/// where the kernel execve's the unmarked interpreter and the script
167/// itself never reaches `bprm_check_security`. The eBPF `file_open` read
168/// branch runs the same allowlist check used at execve against the
169/// script's path; in enforce mode `status` is the LSM verdict (`-1`
170/// blocked). The `filename` carries the script's path and `comm` the
171/// script's basename, so the script — not the interpreter — is the unit
172/// surfaced in logs and soak. Matches `EVENT_KIND_EXECVE` handling.
173pub const EVENT_KIND_SCRIPT_EXEC: u32 = 4;
174
175/// Runtime mode communicated to the eBPF program via the CONFIG map.
176pub const MODE_OBSERVE: u32 = 0;
177pub const MODE_SOAK: u32 = 1; // eBPF behaves like OBSERVE; userspace records paths
178pub const MODE_ENFORCE: u32 = 2;
179
180/// Current schema version of [`OriginRecord`]. Records carrying a different
181/// version are treated as unmarked.
182///
183/// v4 made the record fully hash-based: the variable-length path fields
184/// (`creator_path`, the landing folder, the landing basename) became
185/// `u64` FNV hashes instead of fixed buffers. This lifts the path-length
186/// ceiling (a hash is the same 8 bytes whether the path is 12 or 4096
187/// bytes) and shrinks the record to 64 bytes, well under the xattr
188/// block limit. Human-readable resolution of those hashes lives in the
189/// plaintext audit db (see the `hashdb` userspace module), not in the
190/// record. v3 records (which embedded path strings) are treated as
191/// unmarked and get re-marked on next open.
192pub const ORIGIN_VERSION: u32 = 4;
193
194/// Provenance record. Carried in the `security.bpf.linprov.origin` xattr
195/// and in the INODE_MARKS storage map. Fixed 64 bytes — every
196/// variable-length field is an FNV-1a-64 hash, so the record never
197/// grows with path length and always fits a single xattr block.
198///
199/// Filled in stages:
200/// * BPF `file_open` sets `version`, `pid`, `ts_boot_ns`, `comm`,
201/// `creator_uid`, and the two landing hashes (`landing_folder_hash`,
202/// `landing_basename_hash`), computed in one pass over the landing
203/// path. `creator_path_hash` is left 0 — BPF can't cheaply resolve
204/// the creator's exe path here.
205/// * Userspace, on the corresponding ringbuf event, reads
206/// `/proc/$pid/exe`, fills `creator_path_hash`, and overwrites the
207/// xattr with the augmented record. It also records each hash →
208/// path mapping in the plaintext audit db so logs, soak, and the
209/// user's own `grep` can resolve hashes back to paths.
210///
211/// `creator_path_hash == 0` is the "not yet augmented" sentinel:
212/// `bprm_check_security` reads the storage record first and falls
213/// through to the xattr when it sees a zero creator hash. Rules keyed
214/// on `creator_process` won't match an unaugmented record, but other
215/// dims still do.
216#[repr(C)]
217#[derive(Copy, Clone)]
218#[cfg_attr(feature = "user", derive(bytemuck::Pod, bytemuck::Zeroable))]
219pub struct OriginRecord {
220 pub version: u32,
221 pub pid: u32,
222 pub ts_boot_ns: u64,
223 pub comm: [u8; COMM_LEN],
224 pub creator_uid: u32,
225 pub _pad: u32,
226 /// FNV-1a-64 of the creator's full exe path (`/proc/$pid/exe`).
227 /// 0 until userspace augments the record.
228 pub creator_path_hash: u64,
229 /// FNV-1a-64 of the landing file's immediate parent directory,
230 /// including the trailing `/` (matches `normalize_folder`). Always
231 /// the immediate parent regardless of depth — used for exact
232 /// `landing_folder` matching and for soak/log resolution.
233 pub landing_folder_hash: u64,
234 /// FNV-1a-64 of the landing file's basename (final path component,
235 /// no slash).
236 pub landing_basename_hash: u64,
237 /// FNV-1a-64 of each `/`-terminated ancestor of the landing path
238 /// (shallow → deep), up to [`MAX_FOLDER_ANCESTORS`]. Enables nested
239 /// `landing_folder` matching: a rule whose folder hash equals any
240 /// entry matches. Unused slots are 0.
241 pub landing_ancestor_hashes: [u64; MAX_FOLDER_ANCESTORS],
242}
243
244/// Ring-buffer record. Two kinds:
245/// NetworkFileOpen — informational; eBPF just wrote (or tried to write)
246/// the xattr. `status` is the kfunc return code.
247/// Execve — bprm_check fired AND the file already carried the mark.
248/// `origin` is the record we read back; `status` is unused.
249#[repr(C)]
250#[derive(Copy, Clone)]
251#[cfg_attr(feature = "user", derive(bytemuck::Pod, bytemuck::Zeroable))]
252pub struct Event {
253 pub kind: u32,
254 pub pid: u32,
255 pub tgid: u32,
256 pub status: i32,
257 pub comm: [u8; COMM_LEN],
258 pub origin: OriginRecord,
259 /// The live path: landing path for `NetworkFileOpen`, exec/target
260 /// path for `Execve`. Sized to `PATH_MAX`; transient (ringbuf only).
261 pub filename: [u8; EXEC_PATH_LEN],
262}
263
264impl Event {
265 pub const SIZE: usize = core::mem::size_of::<Self>();
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271
272 #[test]
273 fn fnv_known_vectors() {
274 // FNV-1a-64 offset basis for the empty string.
275 assert_eq!(fnv_hash(""), 0xcbf2_9ce4_8422_2325);
276 // Pre-computed reference values from a separate FNV implementation.
277 assert_eq!(fnv_hash("a"), 0xaf63_dc4c_8601_ec8c);
278 assert_eq!(fnv_hash("foobar"), 0x85944171_f73967e8);
279 }
280
281 #[test]
282 fn fnv_string_and_bytes_agree() {
283 let s = "/usr/bin/curl";
284 assert_eq!(fnv_hash(s), fnv_hash_bytes(s.as_bytes()));
285 }
286
287 #[test]
288 fn dim_flags_are_unique() {
289 let all = [
290 dim::TARGET_FILENAME,
291 dim::TARGET_FOLDER,
292 dim::LANDING_FILENAME,
293 dim::LANDING_FOLDER,
294 dim::CREATOR_PROCESS,
295 dim::CREATOR_COMM,
296 dim::CREATOR_UID,
297 dim::EXECUTION_UID,
298 ];
299 let mut acc = 0u32;
300 for d in all {
301 assert_eq!(d.count_ones(), 1, "each dim is one bit");
302 assert_eq!(acc & d, 0, "dim {d:#b} overlaps with prior {acc:#b}");
303 acc |= d;
304 }
305 }
306
307 #[test]
308 fn origin_record_size_is_v4_expected() {
309 // 4 + 4 + 8 + 16 + 4 + 4 + 8 + 8 + 8 + 8*MAX_FOLDER_ANCESTORS
310 let base = 4 + 4 + 8 + 16 + 4 + 4 + 8 + 8 + 8;
311 assert_eq!(
312 core::mem::size_of::<OriginRecord>(),
313 base + 8 * MAX_FOLDER_ANCESTORS
314 );
315 }
316
317 #[test]
318 fn allow_rule_size_has_no_padding() {
319 // 4 + 4 + 4 + 4 + 16 + 8*5 = 72
320 assert_eq!(core::mem::size_of::<AllowRule>(), 72);
321 }
322
323 #[test]
324 fn fnv_constants_match_reference() {
325 // FNV-1a-64 parameters per http://www.isthe.com/chongo/tech/comp/fnv/
326 assert_eq!(FNV_OFFSET, 0xcbf2_9ce4_8422_2325);
327 assert_eq!(FNV_PRIME, 0x100_0000_01b3);
328 }
329}