linprov 0.3.0

eBPF mark-of-the-web for Linux: tag network-touched files and enforce who can exec them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! Ring-buffer event handler.
//!
//! `NetworkFileOpen` events: read `/proc/$pid/exe` to learn the creator's
//! full exe path, record the path → hash mappings (creator exe, landing
//! folder, landing basename) in the audit db, then write the augmented
//! v4 `OriginRecord` (all hashes) to the `security.bpf.linprov.origin`
//! xattr.
//!
//! `Execve` events (only emitted when the file was marked): log; in
//! enforce mode the LSM verdict in `event.status` tells us whether the
//! exec was blocked; in soak mode we emit one allowlist rule per
//! configured dimension, resolving the record's hashes back to paths via
//! the audit db.

use std::{
    ffi::CString,
    fs,
    os::fd::AsRawFd,
    path::{Path, PathBuf},
};

use linprov_common::{
    Event, OriginRecord, COMM_LEN, EVENT_KIND_DERIVED_FILE_OPEN, EVENT_KIND_EXECVE,
    EVENT_KIND_NETWORK_FILE_OPEN, EVENT_KIND_SCRIPT_EXEC, EXEC_PATH_LEN, MAX_FOLDER_ANCESTORS,
    ORIGIN_VERSION, XATTR_NAME,
};
use log::{debug, info, warn};

use tokio::sync::broadcast;

use crate::{
    allowlist::{rule_from_context, OriginContext, Soak, ALLOW_DIMS},
    control::{BlockEvent, BlocksTable},
    encoding::escape,
    hashdb::HashDb,
    inode_storage::InodeMarks,
    ModeArg,
};

pub struct Config<'a> {
    pub mode: ModeArg,
    pub soak: Option<Soak>,
    pub hashdb: &'a HashDb,
}

pub fn handle_event(
    cfg: &Config,
    inode_marks: &mut InodeMarks,
    blocks: &mut BlocksTable,
    block_tx: &broadcast::Sender<BlockEvent>,
    raw: &[u8],
) {
    if raw.len() < std::mem::size_of::<Event>() {
        warn!(
            "short ring-buf record: got {} bytes, expected {}",
            raw.len(),
            std::mem::size_of::<Event>()
        );
        return;
    }
    let event: &Event =
        match bytemuck::try_from_bytes::<Event>(&raw[..std::mem::size_of::<Event>()]) {
            Ok(e) => e,
            Err(e) => {
                warn!("failed to cast ring-buf record to Event: {e}");
                return;
            }
        };

    match event.kind {
        EVENT_KIND_NETWORK_FILE_OPEN => on_file_marked(cfg, inode_marks, event, false),
        EVENT_KIND_DERIVED_FILE_OPEN => on_file_marked(cfg, inode_marks, event, true),
        EVENT_KIND_EXECVE => on_execve_marked(cfg, blocks, block_tx, event),
        EVENT_KIND_SCRIPT_EXEC => on_script_exec(cfg, blocks, block_tx, event),
        other => warn!("unknown event kind: {other}"),
    }
}

/// Handle a file-marked event. `derived == false` for a network-touched
/// write (the writer is the creator → resolve its exe path); `derived ==
/// true` for a taint-propagated write (e.g. `tar` extracting a marked
/// archive → the record's creator identity is *inherited* and must not be
/// overwritten with the extractor's exe).
fn on_file_marked(cfg: &Config, inode_marks: &mut InodeMarks, event: &Event, derived: bool) {
    let landing_path = c_str_to_string(&event.filename);
    let comm = comm_to_string(&event.comm);
    let target = PathBuf::from(&landing_path);

    if is_pseudo_fs(&target) {
        debug!("skipping non-regular target: {}", target.display());
        return;
    }

    // Start from the BPF-written record (landing hashes already set on the
    // in-kernel storage copy) and fill in what only userspace can resolve.
    let mut augmented: OriginRecord = event.origin;
    augmented.version = ORIGIN_VERSION;

    // Record path → hash mappings in the audit db, and set the same hashes
    // on the record we persist. `HashDb::record` hashes with the same
    // FNV the BPF side uses, so these match the in-kernel storage record
    // (and the allowlist rule hashes).
    //
    // Ancestor hashes (shallow → deep) for nested landing_folder
    // matching — mirrors the BPF walk, including the power-of-two index
    // mask, so the userspace-written xattr and the in-kernel
    // inode_storage record agree byte-for-byte.
    augmented.landing_ancestor_hashes = [0u64; MAX_FOLDER_ANCESTORS];
    let mut count = 0usize;
    for (i, b) in landing_path.bytes().enumerate() {
        if b == b'/' {
            let prefix = &landing_path[..=i]; // includes the trailing '/'
            let h = cfg.hashdb.record(prefix);
            augmented.landing_ancestor_hashes[count & (MAX_FOLDER_ANCESTORS - 1)] = h;
            count += 1;
            // The deepest `/`-prefix is the immediate parent.
            augmented.landing_folder_hash = h;
        }
    }
    if let Some(base) = basename_of(&landing_path) {
        augmented.landing_basename_hash = cfg.hashdb.record(base);
    }

    // Resolve the creator's exe path — but only for fresh (network) marks.
    //
    //   * network: /proc/$pid/exe is the binary the creator was exec'd from.
    //     Best-effort: if the creator already exited we leave
    //     creator_path_hash at 0, and rules keyed on it just won't match.
    //   * derived: the marking process is the *extractor* (e.g. tar), not the
    //     creator — the creator identity is inherited from the source file's
    //     record and must be kept as-is. We only resolve the already-set
    //     hash for the log line.
    let creator_path = if derived {
        cfg.hashdb.resolve(augmented.creator_path_hash)
    } else {
        let p = read_creator_exe(event.pid);
        if let Some(path) = p.as_deref() {
            augmented.creator_path_hash = cfg.hashdb.record(path);
        }
        p
    };

    let value = bytemuck::bytes_of(&augmented).to_vec();
    let kind = if derived {
        "marked (derived)"
    } else {
        "marked"
    };

    // Persist the mark through one no-follow O_PATH fd (see
    // `open_mark_target`). The landing path is a kernel `bpf_d_path` snapshot,
    // and a local user can swap it for a symlink between the event and now;
    // re-walking that path with a symlink-following `xattr::set` would let
    // them redirect this root-privileged write onto a file they don't own
    // (e.g. a system binary), getting it marked and then blocked in enforce
    // mode. Opening once O_PATH|O_NOFOLLOW, gating on a regular file, and
    // writing both the xattr and the INODE_MARKS back-fill through that fd's
    // inode closes that TOCTOU.
    let Some(file) = open_mark_target(&target) else {
        return; // vanished, symlink, or non-regular — open_mark_target logged why
    };

    // Marking a written file is routine and high-volume; log it at DEBUG.
    // INFO is reserved for actual executions (the PROVENANCE-EXEC line in
    // `on_execve_marked`).
    //
    // Write via the /proc/self/fd magic symlink so setxattr lands on the
    // inode the fd already names rather than re-resolving `target` (which
    // can't be raced). fsetxattr rejects O_PATH fds directly, hence the
    // proc path.
    // Escape kernel-derived strings before they hit the log so a crafted
    // filename can't forge log lines (finding #4).
    let target_disp = escape(&landing_path);
    let creator_disp = creator_path.as_deref().map(escape);
    match set_origin_xattr(&file, &value) {
        Ok(()) => debug!(
            "{kind} {target_disp} (pid={} comm={} creator_uid={} creator_path={} ts_boot_ns={})",
            event.pid,
            escape(&comm),
            augmented.creator_uid,
            creator_disp.as_deref().unwrap_or("<unknown>"),
            event.origin.ts_boot_ns
        ),
        Err(e) => debug!("setxattr({target_disp}, {XATTR_NAME}) failed: {e}"),
    }

    // Back-fill the in-kernel INODE_MARKS record with the augmented record so
    // the bprm fast path (which otherwise re-reads the xattr when
    // creator_path_hash == 0) and same-boot taint propagation both carry the
    // full creator identity. Same verified fd → same inode as the xattr
    // above. Best-effort.
    if let Err(e) = inode_marks.backfill(&file, &augmented) {
        debug!("INODE_MARKS back-fill for {} failed: {e}", target.display());
    }
}

/// Open the marked file for the provenance writes (xattr + INODE_MARKS
/// back-fill), returning the fd only if it's a regular file.
///
/// `O_PATH | O_NOFOLLOW`: the landing path is a kernel snapshot a local user
/// can swap after the event. `O_NOFOLLOW` makes a symlink at the final
/// component yield an fd to the *link itself* (S_ISLNK), which the
/// regular-file gate below rejects — so the root daemon can't be redirected
/// onto a file the user couldn't otherwise write. `O_PATH` keeps the open
/// free of side effects and non-blocking, so a fifo/device swapped into the
/// path can't stall the daemon (and O_PATH does not fire
/// `security_file_open`, so it can't re-taint the daemon either). Callers
/// write the xattr via `/proc/self/fd/N` and back-fill through this same fd,
/// so both target the inode the fd names rather than re-resolving the path.
///
/// Failures (file renamed/removed between the event and now, a symlink or
/// non-regular target, an fs without inode storage) are non-fatal: log and
/// skip. The durable mark only matters for files that get exec'd / read,
/// which are regular files.
fn open_mark_target(target: &Path) -> Option<fs::File> {
    use std::os::unix::fs::OpenOptionsExt;

    // read(true) only satisfies std's "an access mode is required"; O_PATH
    // overrides it in the kernel, yielding a path-only fd.
    let file = match fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(target)
    {
        Ok(f) => f,
        Err(e) => {
            debug!(
                "O_PATH open of {} to persist mark failed: {e}",
                target.display()
            );
            return None;
        }
    };

    // Only regular files carry execution provenance. A symlink fd (from
    // O_PATH|O_NOFOLLOW), directory, fifo, device, or socket is rejected —
    // a swapped-in non-regular target is exactly the redirect we're closing.
    match file.metadata() {
        Ok(m) if m.file_type().is_file() => Some(file),
        Ok(_) => {
            debug!("skipping non-regular mark target {}", target.display());
            None
        }
        Err(e) => {
            debug!("fstat of {} failed: {e}", target.display());
            None
        }
    }
}

/// Write the `security.bpf.linprov.origin` xattr onto the inode behind
/// `file` (a verified-regular `O_PATH` fd from [`open_mark_target`]).
///
/// We can't `fsetxattr` an `O_PATH` fd (EBADF), and the `xattr` crate's path
/// `set` is *no-follow* — it would target the `/proc/self/fd/N` magic symlink
/// itself, which procfs can't hold an xattr on (ENOTSUP). So call
/// `libc::setxattr` directly on the proc path: it follows the magic symlink
/// to the fd's real inode. That follow is of the kernel's own `/proc` link,
/// not the attacker-controlled landing path, so it stays TOCTOU-safe.
fn set_origin_xattr(file: &fs::File, value: &[u8]) -> std::io::Result<()> {
    let proc_path = CString::new(format!("/proc/self/fd/{}", file.as_raw_fd()))
        .expect("/proc/self/fd path has no interior NUL");
    let name = CString::new(XATTR_NAME).expect("XATTR_NAME has no interior NUL");
    // SAFETY: `proc_path`/`name` are valid NUL-terminated C strings live for
    // the call; `value`/`value.len()` describe a valid byte buffer.
    let ret = unsafe {
        libc::setxattr(
            proc_path.as_ptr(),
            name.as_ptr(),
            value.as_ptr() as *const libc::c_void,
            value.len(),
            0,
        )
    };
    if ret == 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

fn read_creator_exe(pid: u32) -> Option<String> {
    let link = format!("/proc/{pid}/exe");
    match fs::read_link(&link) {
        Ok(p) => Some(p.to_string_lossy().into_owned()),
        Err(e) => {
            debug!("read_link({link}) failed: {e}");
            None
        }
    }
}

fn is_pseudo_fs(target: &std::path::Path) -> bool {
    let Some(s) = target.to_str() else {
        return true;
    };
    s.starts_with("/dev/")
        || s.starts_with("/proc/")
        || s.starts_with("/sys/")
        || s.starts_with("/run/")
}

fn on_execve_marked(
    cfg: &Config,
    blocks: &mut BlocksTable,
    block_tx: &broadcast::Sender<BlockEvent>,
    event: &Event,
) {
    let target_path = c_str_to_string(&event.filename);
    let exec_comm = comm_to_string(&event.comm);
    let creator_comm = comm_to_string(&event.origin.comm);

    // Resolve the record's hashes back to human-readable paths via the
    // audit db. `None` means the db doesn't know this hash (e.g. it was
    // pruned, or the creator exited before it could be recorded).
    let creator_path = cfg.hashdb.resolve(event.origin.creator_path_hash);
    let landing_folder = cfg.hashdb.resolve(event.origin.landing_folder_hash);
    let landing_basename = cfg.hashdb.resolve(event.origin.landing_basename_hash);

    if event.status != 0 {
        let token = record_block_token(
            blocks,
            block_tx,
            "exec",
            event,
            &target_path,
            &landing_folder,
            &landing_basename,
            &creator_path,
            &creator_comm,
        );
        warn!(
            "BLOCKED-EXEC target={} landing_folder={} landing_file={} pid={} comm={} origin={} (LSM verdict {}) [allow: {token}]",
            escape(&target_path),
            resolved(&landing_folder, event.origin.landing_folder_hash),
            resolved(&landing_basename, event.origin.landing_basename_hash),
            event.pid,
            escape(&exec_comm),
            format_origin(&event.origin, &creator_comm, &creator_path),
            event.status,
        );
        return;
    }

    info!(
        "PROVENANCE-EXEC target={} landing_folder={} landing_file={} pid={} comm={} origin={}",
        escape(&target_path),
        resolved(&landing_folder, event.origin.landing_folder_hash),
        resolved(&landing_basename, event.origin.landing_basename_hash),
        event.pid,
        escape(&exec_comm),
        format_origin(&event.origin, &creator_comm, &creator_path),
    );

    maybe_soak(
        cfg,
        event,
        &target_path,
        &landing_folder,
        &landing_basename,
        &creator_path,
        &creator_comm,
    );
}

/// Handle a script-exec event: a marked file opened for read by a known
/// interpreter (`bash foo.sh` / `python foo.py` / `. foo.sh`). The script
/// — not the interpreter — is the unit: `event.filename` is the script
/// path and drives allowlist matching exactly like an execve; the
/// interpreter's `comm` is carried for context. `status != 0` means the
/// LSM denied the read (enforce). Mirrors `on_execve_marked`, including
/// soak rule emission keyed on the script path, so a
/// `target_filename=<script>` / `target_folder=<dir>` rule permits the
/// script under any interpreter and under `./script` (shebang) alike.
fn on_script_exec(
    cfg: &Config,
    blocks: &mut BlocksTable,
    block_tx: &broadcast::Sender<BlockEvent>,
    event: &Event,
) {
    let script_path = c_str_to_string(&event.filename);
    let interp_comm = comm_to_string(&event.comm);
    let creator_comm = comm_to_string(&event.origin.comm);

    let creator_path = cfg.hashdb.resolve(event.origin.creator_path_hash);
    let landing_folder = cfg.hashdb.resolve(event.origin.landing_folder_hash);
    let landing_basename = cfg.hashdb.resolve(event.origin.landing_basename_hash);
    let script_name = basename_of(&script_path).unwrap_or(&script_path);

    if event.status != 0 {
        let token = record_block_token(
            blocks,
            block_tx,
            "script",
            event,
            &script_path,
            &landing_folder,
            &landing_basename,
            &creator_path,
            &creator_comm,
        );
        warn!(
            "BLOCKED-SCRIPT script={} name={} interp={} landing_folder={} landing_file={} pid={} origin={} (LSM verdict {}) [allow: {token}]",
            escape(&script_path),
            escape(script_name),
            escape(&interp_comm),
            resolved(&landing_folder, event.origin.landing_folder_hash),
            resolved(&landing_basename, event.origin.landing_basename_hash),
            event.pid,
            format_origin(&event.origin, &creator_comm, &creator_path),
            event.status,
        );
        return;
    }

    info!(
        "PROVENANCE-SCRIPT script={} name={} interp={} landing_folder={} landing_file={} pid={} origin={}",
        escape(&script_path),
        escape(script_name),
        escape(&interp_comm),
        resolved(&landing_folder, event.origin.landing_folder_hash),
        resolved(&landing_basename, event.origin.landing_basename_hash),
        event.pid,
        format_origin(&event.origin, &creator_comm, &creator_path),
    );

    maybe_soak(
        cfg,
        event,
        &script_path,
        &landing_folder,
        &landing_basename,
        &creator_path,
        &creator_comm,
    );
}

/// Build the candidate "allow" rule for a blocked exec (the most-specific
/// rule that would have permitted it — see `ALLOW_DIMS`), record it in the
/// blocks table, and return its stable token. The token goes in the
/// `BLOCKED-*` log line so an operator can `linprov allow <token>`.
#[allow(clippy::too_many_arguments)]
fn record_block_token(
    blocks: &mut BlocksTable,
    block_tx: &broadcast::Sender<BlockEvent>,
    kind: &'static str,
    event: &Event,
    target: &str,
    landing_folder: &Option<String>,
    landing_basename: &Option<String>,
    creator_path: &Option<String>,
    creator_comm: &str,
) -> String {
    let exec_uid = get_uid_for_pid(event.pid).unwrap_or(0);
    let ctx = OriginContext {
        target_filename: target,
        landing_folder: landing_folder.as_deref(),
        landing_basename: landing_basename.as_deref(),
        creator_path: creator_path.as_deref(),
        creator_comm,
        creator_uid: event.origin.creator_uid,
        execution_uid: exec_uid,
    };
    let token = blocks.record(rule_from_context(&ctx, ALLOW_DIMS).to_line());

    // Fan out to any control-socket subscribers (the tray agent). A
    // non-blocking send; `Err(NoReceivers)` is the common case (no agent
    // connected) and is ignored.
    let creator = creator_path
        .clone()
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| creator_comm.to_string());
    let _ = block_tx.send(BlockEvent {
        kind,
        token: token.clone(),
        target: target.to_string(),
        creator,
    });
    token
}

/// In soak mode, emit one allowlist rule for this event keyed on `target`
/// (the live exec path for execve, the script path for script-exec) plus
/// the record-resolved landing/creator dims. Shared by `on_execve_marked`
/// and `on_script_exec`.
#[allow(clippy::too_many_arguments)]
fn maybe_soak(
    cfg: &Config,
    event: &Event,
    target: &str,
    landing_folder: &Option<String>,
    landing_basename: &Option<String>,
    creator_path: &Option<String>,
    creator_comm: &str,
) {
    if cfg.mode != ModeArg::Soak {
        return;
    }
    let Some(soak) = cfg.soak.as_ref() else {
        return;
    };
    let exec_uid = get_uid_for_pid(event.pid).unwrap_or(0);
    let ctx = OriginContext {
        target_filename: target,
        landing_folder: landing_folder.as_deref(),
        landing_basename: landing_basename.as_deref(),
        creator_path: creator_path.as_deref(),
        creator_comm,
        creator_uid: event.origin.creator_uid,
        execution_uid: exec_uid,
    };
    match soak.record(&ctx) {
        Ok(Some(line)) => info!("soak: added `{line}`"),
        Ok(None) => {}
        Err(e) => warn!("soak append failed: {e}"),
    }
}

fn get_uid_for_pid(pid: u32) -> Option<u32> {
    let s = fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
    for line in s.lines() {
        if let Some(rest) = line.strip_prefix("Uid:") {
            // Uid: <real> <effective> <saved> <fs>
            let real = rest.split_whitespace().next()?;
            return real.parse().ok();
        }
    }
    None
}

/// Render a db-resolved value, or the raw hash if it couldn't be
/// resolved (so logs stay actionable: `grep <hash> hashes.tsv`).
fn resolved(s: &Option<String>, hash: u64) -> String {
    match s {
        Some(v) => escape(v), // db-resolved path → escape for safe logging
        None if hash == 0 => "<none>".to_string(),
        None => format!("<hash:{hash:016x}>"),
    }
}

fn format_origin(o: &OriginRecord, creator_comm: &str, creator_path: &Option<String>) -> String {
    format!(
        "{{v:{},ts_boot_ns:{},pid:{},uid:{},comm:{},creator:{}}}",
        o.version,
        o.ts_boot_ns,
        o.pid,
        o.creator_uid,
        escape(creator_comm),
        resolved(creator_path, o.creator_path_hash),
    )
}

fn comm_to_string(comm: &[u8; COMM_LEN]) -> String {
    let end = comm.iter().position(|&b| b == 0).unwrap_or(comm.len());
    String::from_utf8_lossy(&comm[..end]).into_owned()
}

fn c_str_to_string(buf: &[u8; EXEC_PATH_LEN]) -> String {
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    String::from_utf8_lossy(&buf[..end]).into_owned()
}

/// Final path component (basename), no slash. `None` for empty input or
/// a trailing-slash path (which has no basename).
fn basename_of(path: &str) -> Option<&str> {
    let base = path.rsplit_once('/').map(|(_, b)| b).unwrap_or(path);
    if base.is_empty() {
        None
    } else {
        Some(base)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn open_mark_target_accepts_regular_file() {
        let dir = tempfile::tempdir().unwrap();
        let f = dir.path().join("reg");
        std::fs::write(&f, b"x").unwrap();
        assert!(open_mark_target(&f).is_some());
    }

    #[test]
    fn open_mark_target_rejects_symlink() {
        // The core of the TOCTOU fix (#1): a symlink swapped into the
        // landing path must NOT be followed to its (possibly unowned)
        // target — O_NOFOLLOW yields an fd to the link itself, which the
        // regular-file gate rejects.
        let dir = tempfile::tempdir().unwrap();
        let victim = dir.path().join("victim");
        std::fs::write(&victim, b"x").unwrap();
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&victim, &link).unwrap();
        assert!(open_mark_target(&link).is_none());
    }

    #[test]
    fn open_mark_target_rejects_directory_and_missing() {
        let dir = tempfile::tempdir().unwrap();
        assert!(open_mark_target(dir.path()).is_none());
        assert!(open_mark_target(Path::new("/nonexistent/linprov/x")).is_none());
    }

    #[test]
    fn basename_split() {
        assert_eq!(basename_of("/a/b/foo.sh"), Some("foo.sh"));
        assert_eq!(basename_of("/foo"), Some("foo"));
        assert_eq!(basename_of("/a/b/"), None);
    }

    #[test]
    fn ancestor_prefixes_shallow_to_deep() {
        // The byte loop in on_file_marked produces these `/`-prefixes.
        let path = "/a/b/c/foo";
        let prefixes: Vec<&str> = path
            .bytes()
            .enumerate()
            .filter(|(_, b)| *b == b'/')
            .map(|(i, _)| &path[..=i])
            .collect();
        assert_eq!(prefixes, vec!["/", "/a/", "/a/b/", "/a/b/c/"]);
    }
}