Port parse_freebsd_status into (jsecmon freebsd-parse)
ober
7301fe33d3c5630f178c9a2e1c91a954e09d694e
--- a/README.md +++ b/README.md @@ -129,7 +129,7 @@ then crypto orchestration, then I/O / async / FFI (monitors, server, storage). | `dtrace::consumer::EventParser` (DTrace line parser) | `jsecmon/dtrace-parse.ss` | ✅ **untyped layer** — `parse_dtrace_line(line)`: split a `SECMON\|TYPE\|…` DTrace line on `\|` and dispatch on `parts[1]` into a per-type structured record (EXEC/EXIT/CONNECT/LISTEN/OPEN/WRITE) with each handler's exact field extraction; a <2-field / unknown-type / too-few-fields line yields no record (`#f`), matching secmon's `return Ok(())` no-ops. A text parser yielding a structured record, like the DNS/SELinux parsers, so untyped (alist, since the per-type fields are disjoint). Numeric fields use `.parse().unwrap_or(0)` (u32 rejects negatives → 0; exit code is i32), and the EXEC cmdline is `split_whitespace`. **Composes** `(jsecmon sensitive-path)` for the OPEN `sensitive?` gate. `make dtrace-parse-check` reproduces secmon's `test_parse_exec_line` / `test_parse_exit_line` + the other four formats + the no-event and `unwrap_or(0)` corners. (The stateful parts — process cache, suspicious-exec dispatch, channel send — are the deferred consumer loop.) | | `platform::{linux,freebsd}` (`is_dangerous_path` + `get_mounts` parsers) | `jsecmon/platform-mounts.ss` | ✅ **untyped layer** — the pure halves of each `IsolationProvider`, reads stripped: `is_dangerous_path` is **exact** membership in the platform's dangerous-path set (Linux 12 entries incl. `/proc/kcore`, `/dev/mem`, the docker/crio/containerd sockets; FreeBSD 6 incl. `/dev/io`, `devd.pipe`; unknown platforms empty, per the `UnsupportedProvider` default), and `parse_mounts` reproduces each `get_mounts` line loop — Linux `split_whitespace` keeping field[1], FreeBSD `split(" on ")` keeping piece[1] minus a trailing ` (opts)`. Pins that membership is exact not prefix (`/host/foo` is clean), and that the FreeBSD split takes piece[1] of a multi-`" on "` split (not everything-after-first). obfstr!-hidden lists decode to these plaintexts. Pure — the `/proc/self/mounts` read / `mount` exec is the deferred I/O — no native lib; secmon has no `#[test]` here so `make platform-mounts-check` asserts against the Rust source. (The `container.rs` test-only mock `is_dangerous_path` is `#[cfg(test)]` scaffolding, not ported.) | | `platform::linux` (/proc parsers) | `jsecmon/proc-linux.ss` | ✅ **untyped layer** — the pure parsing helpers with the file reads stripped: `parse_stat` (comm between first `(` and **last** `)`, ppid the 2nd field after `") "`), `parse_uid` (first `Uid:` line, 2nd field), `hex_to_state` (TCP state table → `UNKNOWN`), `parse_ipv4` (little-endian hex → dotted quad), `parse_ipv6` (32-hex → 8 groups), `parse_addr` (`HEXADDR:HEXPORT`, ipv6 when protocol contains `6`). Pure text/number parsing, so untyped. `parse_stat`/`parse_uid` use `.parse::<u32>().ok()` so failure is `#f` (not 0) and negatives are rejected; `parse_ipv4` rejects >`0xFFFFFFFF`; ports are u16. Also `parse_security_environ` (from `ebpf/loader.rs`, but functionally a `/proc/[pid]/environ` parser): splits the NUL-separated blob, drops empty and non-UTF-8 entries (faithful to `std::str::from_utf8(..).ok()`, reproduced exception-free by a lossy-decode→re-encode→compare round trip), and keeps any var whose name `starts_with` one of 19 security-relevant prefixes **or** whose `to_uppercase()` does — so a lower-cased `path=`/`ld_…` still matches the upper-cased prefixes, while `http_proxy`/`https_proxy` match only literally-lower vars. `make proc-linux-check` reproduces secmon's five linux.rs tests + ipv6/parse-addr + a comm-with-paren corner + 10 environ-scan cases (invalid-UTF-8 drop, uppercase-arm, trailing NUL). (The `/proc` reads and inode→pid scan are the deferred I/O.) | -| `platform::freebsd` (parsers) | `jsecmon/freebsd-parse.ss` | ✅ **untyped layer** — the pure parsing helpers with the command/file reads stripped: `parse_kldstat_line` (≥5 whitespace fields, name is `parts[4]`, size is `parts[3]` as hex with optional `0x`, size `None` on non-hex via `.ok()`, action always `Loaded`) and `parse_address` (`addr:port` split at the **last** `:`, `[ipv6]:port` split at the first `]`, `*` address → `0.0.0.0`, `*` port → `0`). Ports here are **DECIMAL** u16 (`.parse()`), unlike Linux's hex `/proc/net`. Plus `parse_ps_line` (the `ps -axo pid,ppid,uid,comm,args` fallback parser: ≥5 ws fields, `pid`/`ppid`/`uid` as u32 via `.parse().ok()?` so a non-u32 field rejects the whole line, `comm` is field[3], `args` is field[4..] re-joined with single spaces). Pure text/number parsing, so untyped. Also `parse_sockstat_line` (cols `USER COMMAND PID FD PROTO LOCAL FOREIGN`, ≥7, `pid` as u32-or-reject, protocol lower-cased, a `FOREIGN` of exactly `*:*` short-circuits to `("0.0.0.0" . 0)` **without** `parse_address`, `state` = LISTEN when remote is `0.0.0.0`/`::`/port 0 else ESTABLISHED) and `parse_netstat_line` (cols `Proto Recv-Q Send-Q LOCAL FOREIGN [state]`, ≥5, here `*:*` **does** go through `parse_address`, `state` = `parts[5]` or `UNKNOWN`, no pid/name) — both producing a connection alist mirroring `ConnectionInfo`. `make freebsd-parse-check` reproduces secmon's three freebsd.rs tests + ipv6/wildcard/negatives + the ps-line cases + the sockstat/netstat rows traced from source. (The `kldstat`/`sockstat`/`netstat`/`ps` command runs are the deferred I/O.) | +| `platform::freebsd` (parsers) | `jsecmon/freebsd-parse.ss` | ✅ **untyped layer** — the pure parsing helpers with the command/file reads stripped: `parse_kldstat_line` (≥5 whitespace fields, name is `parts[4]`, size is `parts[3]` as hex with optional `0x`, size `None` on non-hex via `.ok()`, action always `Loaded`) and `parse_address` (`addr:port` split at the **last** `:`, `[ipv6]:port` split at the first `]`, `*` address → `0.0.0.0`, `*` port → `0`). Ports here are **DECIMAL** u16 (`.parse()`), unlike Linux's hex `/proc/net`. Plus `parse_ps_line` (the `ps -axo pid,ppid,uid,comm,args` fallback parser: ≥5 ws fields, `pid`/`ppid`/`uid` as u32 via `.parse().ok()?` so a non-u32 field rejects the whole line, `comm` is field[3], `args` is field[4..] re-joined with single spaces). Pure text/number parsing, so untyped. Also `parse_sockstat_line` (cols `USER COMMAND PID FD PROTO LOCAL FOREIGN`, ≥7, `pid` as u32-or-reject, protocol lower-cased, a `FOREIGN` of exactly `*:*` short-circuits to `("0.0.0.0" . 0)` **without** `parse_address`, `state` = LISTEN when remote is `0.0.0.0`/`::`/port 0 else ESTABLISHED) and `parse_netstat_line` (cols `Proto Recv-Q Send-Q LOCAL FOREIGN [state]`, ≥5, here `*:*` **does** go through `parse_address`, `state` = `parts[5]` or `UNKNOWN`, no pid/name) — both producing a connection alist mirroring `ConnectionInfo`. Plus `parse_freebsd_status` (the procfs `/proc/[pid]/status` columns: ≥13 ws fields → `(name ppid uid)`, name is `parts[0]`, ppid is `parts[2]`, uid is `parts[12]` = ruid, both u32-or-reject, trailing group columns ignored). `make freebsd-parse-check` reproduces secmon's three freebsd.rs tests + ipv6/wildcard/negatives + the ps-line cases + the sockstat/netstat rows + the status columns traced from source. (The `kldstat`/`sockstat`/`netstat`/`ps`/`status` command/file reads are the deferred I/O.) | | `event_json` + `local_store` (tables) | `jsecmon/event-meta.ss` | ✅ **untyped layer** — the pure classification tables lifted out of the payload-carrying `EventType` enum: `event_json.rs` `get_event_json_data`'s **display severity** (25 constant arms as a name→severity table, + the 7 payload-dependent arms as named helpers taking the deciding field — `auth`/`privilege_change`/`mount`/`capability`/`podman`/`selinux`/`lateral_movement`), and `local_store.rs` `event_severity_u8`'s **coarse store priority** 0..3, which is an *independent* scale (e.g. `privilege_escalation` is `critical` for display but `0` for the store). secmon has no `#[test]` here, so `make event-meta-check` asserts both full tables arm-for-arm against the Rust source. (The JSON payload bodies stay with the I/O layer that owns the event structs.) | | `config` | `jsecmon/config.ss` | ✅ **untyped layer** — `AgentConfig`'s pure parts: the defaults (`0.0.0.0:31337`, poll `100`ms, buffer `10000`), the `from_env` merge (overwrites `listen_addr` on any present value but only overwrites poll/buffer when the value parses as strict u64 — a bad value **keeps the default**, it is not zeroed), and `local_db_path`/`local_key_path` (env override, else `/opt/secmon/{events.db,local.key}` on linux+freebsd, else the `./secmon_*` cwd fallback). Parameterized over a `getenv` callback + a `platform` symbol so the env reads stay deferred I/O; the build.rs-embedded secrets (`get_public_key`/`get_psk`/`is_debug_mode`) belong to the build/FFI phase, not this layer. secmon has no tests here, so `make config-check` asserts the behaviour against the Rust source. | | `monitor/events` (danger predicates) | `jsecmon/event-danger.ss` | ✅ **untyped layer** — the payload predicates that drive a mount/capability event's severity, lifted off their structs: `MountEventInfo::is_dangerous` (`mount-danger-reason source target` → reason string, with the faithful corner that the `/` source entry's prefix is `//` so a plain `/foo` is **not** flagged, and dangerous *targets* match exact-only) and `CapabilityEventInfo::dangerous_caps` (`cap_effective` bits → cap names in the Rust push order, full u64 so bits 38/39 work). These compute the booleans `event-meta`'s mount/capability severity helpers consume. Pure, no native lib; `make event-danger-check` asserts against the Rust source. | --- a/examples/freebsd_parse_check.ss +++ b/examples/freebsd_parse_check.ss @@ -114,6 +114,25 @@ (cinfo "udp" "0.0.0.0" 80 "0.0.0.0" 0 "UNKNOWN" #f #f)) (check "too few cols -> #f" (parse-netstat-line "tcp 0 0 1.2.3.4:5" "tcp") #f) +;; ── parse-freebsd-status: /proc/[pid]/status columns -> (name ppid uid) ─────── +(displayln "parse-freebsd-status:") +(check "basic 13-field" + (parse-freebsd-status + "bash 4321 4000 4321 4321 -1,-1 noflags 1700000000,0 0,0 0,0 wait 1001 1000") + '("bash" 4000 1000)) +;; extra trailing group columns are ignored; uid is the 13th field (ruid) +(check "extra group cols ignored" + (parse-freebsd-status "sshd 100 1 100 100 -1,-1 ctty 0,0 0,0 0,0 - 0 0 0 0 wheel") + '("sshd" 1 0)) +(check "too few (<13) -> #f" + (parse-freebsd-status "bash 1 2 3 4 5 6 7 8 9 10 11") #f) ;; 12 fields +(check "non-u32 ppid -> #f" + (parse-freebsd-status "bash 4321 xx 4321 4321 -1,-1 f 0,0 0,0 0,0 w 1001 1000") #f) +(check "non-u32 ruid -> #f" + (parse-freebsd-status "bash 4321 4000 4321 4321 -1,-1 f 0,0 0,0 0,0 w 1001 zz") #f) +(check "negative ppid -> #f" + (parse-freebsd-status "bash 4321 -5 4321 4321 -1,-1 f 0,0 0,0 0,0 w 1001 1000") #f) + (newline) (if (= fails 0) (displayln "OK: freebsd-parse matches secmon's freebsd.rs behaviour.") --- a/jsecmon/freebsd-parse.ss +++ b/jsecmon/freebsd-parse.ss @@ -9,6 +9,7 @@ ;;; -> (pid ppid uid comm args) | #f ;;; parse-sockstat-line : a `sockstat` row -> connection alist | #f ;;; parse-netstat-line : a `netstat -an` row -> connection alist | #f +;;; parse-freebsd-status: /proc/[pid]/status -> (name ppid uid) | #f ;;; ;;; Pure text/number parsing, like the Linux /proc parsers, so untyped. ;;; @@ -41,7 +42,7 @@ (library (jsecmon freebsd-parse) (export parse-kldstat-line parse-address parse-ps-line - parse-sockstat-line parse-netstat-line) + parse-sockstat-line parse-netstat-line parse-freebsd-status) (import (except (chezscheme) make-hash-table hash-table? sort sort! @@ -167,6 +168,19 @@ remote-addr remote-port state pid process-name))))))))))) + ;; FreeBSD /proc/[pid]/status whitespace columns: + ;; comm pid ppid pgid sid tty_dev flags start user_time sys_time wchan euid ruid … + ;; -> (name ppid uid) | #f. Needs >=13 fields; name is parts[0] verbatim, ppid is + ;; parts[2], uid is parts[12] (ruid). ppid/uid are u32 (Rust `.parse().ok()?`, so a + ;; non-u32 in either rejects the whole row); trailing group columns are ignored. + (def (parse-freebsd-status content) + (let ((parts (ws-tokens content))) + (and (>= (length parts) 13) + (let ((ppid (parse-u32-opt (list-ref parts 2))) + (uid (parse-u32-opt (list-ref parts 12)))) + (and ppid uid + (list (list-ref parts 0) ppid uid)))))) + ;; a `netstat -an` row -> connection alist | #f. protocol is supplied by the ;; caller (secmon passes "tcp" / "udp"). (def (parse-netstat-line line protocol)