After Dark Systems / Service Automation HubCompletely Programmable Infrastructure

OpenSAH / Host security

systemapi-security: the host security service.

One process on one Linux host, answering only on a Unix socket. Every call carries a short-lived signed grant. It keeps an append-only audit chain with a local anchor and a signed head for off-host witnesses, runs a host IDS and distro security checks, and pages high findings without host detail.

Early development unversioned No packaged releases Linux only

What it is and is not

Local host security service for one Linux machine. The binary is secsvc. It listens on a Unix socket, checks secsvc/2 Ed25519 grants, keeps an append-only audit chain in capped segments with a local anchor (audit.head) and a signed head plus stored witnesses for an off-host anchor (root can still rewrite every local file; the agent side that collects heads is built on systemapi.io main, not yet deployed), and runs a host IDS plus configurable distro security modules. High findings page through ntfy.sh without host detail.

sah means Service Automation Hub. This repository is its own module, github.com/afterdarksys/systemapi-security.

This is a local host service. Suite enrollment stays in systemapi. Packet inspection is out of scope. sahcore stays docs-only. The control-plane audit stays in systemapi. secsvc does not import sash, adssh, or systemapi.

secsvc is one process on one host. sahinit supervises it when that supervisor is PID 1. The process answers HTTP over a Unix socket. Grants are secsvc/2 Ed25519 documents. The daemon stores the public key and spends each lease id once. The audit chain is the host record.

Current scope. secsvc runs on one Linux host and is in early development. Built, not yet deployed: the SystemAPI agent and control-plane side that fetches signed audit heads and posts witnesses is on systemapi.io main; until it runs, root on the host can still rewrite every local file. Planned: the security sash verb, which is a contract only and not in the sash command table. Not in this release: remote reporting, package or CVE scanning, firewall rule evaluation, malware signatures, compliance certification and automatic repairs. Packet inspection is out of scope. All six distro profiles have fixture tests and Debian, Ubuntu, Rocky and Alpine passed container smoke tests; native host and service-manager validation has not been done.

Build

go build -o secsvc ./cmd/secsvc
# or: ./build.sh

The module needs Go 1.26.0 or later. Linux amd64 and arm64 binaries can be cross-compiled with CGO_ENABLED=0 GOOS=linux GOARCH=... go build ./cmd/secsvc. Run the tests and vet with:

go test -count=1 -race ./...
go vet ./...

Install and run

Under sahinit

The shipped unit is units/secsvc.json. It omits an execution identity and inherits the supervisor's identity. Current sahinit supports numeric execution.uid, execution.gid, and supplementary execution.groups; provision access to the configured scan inputs, state directory, and socket before selecting a dedicated identity. The unit ships --host "" because sahinit does not expand variables: set it to the host name the grants carry. serve refuses an empty host, a loopback name such as localhost, or an IP literal with host_unset, so an unedited unit does not start. An operator can run secsvc serve under sahinit's userspace supervisor or another supervisor without replacing PID 1.

{
  "name": "secsvc",
  "exec": ["/usr/local/bin/secsvc", "serve", "--dir", "/var/lib/secsvc", "--pub", "/etc/secsvc/pub.hex", "--host", "", "--socket", "/run/secsvc/sock", "--interval", "30s"],
  "type": "simple",
  "ready": "notify",
  "restart": "on-failure",
  "timeout": "30s",
  "boot": true,
  "sandbox": {
    "no_new_privs": true,
    "read_only_paths": ["/etc", "/usr", "/var/log"],
    "read_write_paths": ["/var/lib/secsvc", "/run/secsvc"]
  }
}

sahinit plan accepts units/secsvc.json when that directory contains only the unit file.

systemd and OpenRC templates

These are installable templates; no service is installed or enabled by this repository change. Build secsvc for the target Linux architecture and install it as /usr/local/bin/secsvc. Provision /etc/secsvc/pub.hex using the existing key workflow. Set a host name matching signed grants before starting the service: SECSVC_HOST in service.env or secsvc_host in conf.d/secsvc. Neither has a default; secsvc serve refuses an empty host, a loopback name such as localhost, or an IP literal with host_unset. The daemon does not need the signing seed.

systemd: Debian, Ubuntu, Red Hat, Rocky, Arch

Install systemd/secsvc.service at /etc/systemd/system/secsvc.service and a completed systemd/service.env.example at /etc/secsvc/service.env (root owned, mode 0600). Then run systemctl daemon-reload and systemctl enable --now secsvc. State/runtime directories are created by systemd. The template runs as root to inspect local account and security state, restricts writes to daemon state, and keeps host network and PID 1 views. Custom integrity watches requiring writes are not part of this service. If narrowing privileges, verify per-check coverage.

OpenRC: Alpine

Install openrc/secsvc at /etc/init.d/secsvc with mode 0755 and a completed openrc/secsvc.confd at /etc/conf.d/secsvc (root owned, mode 0600). Run rc-update add secsvc default and rc-service secsvc start. The foreground process is managed by supervise-daemon; required directories are created by checkpath. OpenRC variants can use this template on other supported distros.

Configuring and verifying a template install

Start with modules off, then apply an example through the authenticated config API; see Distro security modules. Inspect call report and call status after the first scan. Containers, missing optional tools/files, MAC policy, and supervisor sandboxing can reduce coverage; the report exposes that explicitly. These service templates require native service-manager smoke testing before rollout.

The existing units/secsvc.json remains the sahinit template. Use the supervisor appropriate to the target system; only one process should own a state directory and socket.

Reference: systemd execution settings.

Operator quick start

secsvc keygen --seed-out /etc/secsvc/seed
secsvc grant --seed /etc/secsvc/seed --actor ops --host HOST \
  --purpose security:operate --ttl 10m --lease lease-op0001
secsvc serve --dir /var/lib/secsvc --pub /etc/secsvc/pub.hex \
  --host HOST --socket /run/secsvc/sock --interval 30s
secsvc call status --socket /run/secsvc/sock --grant /tmp/grant.json
secsvc audit verify --dir /var/lib/secsvc
secsvc audit anchor --dir /var/lib/secsvc   # once, for a chain from before audit.head
secsvc audit migrate --dir /var/lib/secsvc  # once, daemon stopped, for a single-file chain

The ntfy topic in the contact is a bearer: anyone who learns or guesses it reads every page. Treat it as a secret. Pages carry only a kind, a count and a reference unless page_detail is on.

keygen prints the public key as 64 hex characters and writes the seed with O_EXCL at mode 0600. The seed is not printed. grant checks policy before it loads the seed or signs. A purpose with no --entitlement flags receives that purpose's full ceiling. --ttl is a whole number of seconds, at most 15m.

call sends X-Secsvc-Grant and does not verify the document itself. The daemon does. A contact file must be a regular file at mode 0600. Config and contact text stay off stderr. Exit 0 prints the API JSON. Exit 2 is usage or local configuration. Exit 1 is a refusal or a failed call. The first stderr line is a stable code from internal/codes.

serve exits 0 after SIGINT or SIGTERM. Any serve error, including --interval under 5s, exits 2 and prints the code. An interval under 5s returns before the state directory is created.

Command-line reference

This table summarizes internal/cli/cli.go at the documented commit. Every command exits 2 for usage or local configuration, 1 for a refusal, a failed call or a failed audit check, and 0 on success; the first stderr line is a stable code from internal/codes.

command flags what
secsvc keygen --seed-out PATH (required) Writes a new Ed25519 seed with O_EXCL at mode 0600 and prints the public key as 64 hex characters.
secsvc grant --seed, --actor, --host, --purpose, --ttl (required); --lease; --entitlement and --watch (each repeatable) Prints a signed secsvc/2 grant. --purpose is security:read, security:config, security:operate or security:witness. --ttl is a Go duration of whole seconds, at most 15m. Without --lease a random 32-hex-digit lease id is used. Without --entitlement the purpose's full ceiling is granted. At most 16 entitlements and 64 watch paths; * is grant_star and / is grant_root_slash.
secsvc serve --dir, --pub, --socket (required); --host; --interval (default 30s, at least 5s) Runs the daemon. An empty or missing --host, a loopback name, a name under .localhost or an IP literal is host_unset; a malformed name is bad_host.
secsvc call VERB --socket, --grant (required); --file (only for config-set); --contact-file (only for contact) Sends one request with the grant in X-Secsvc-Grant and prints the API JSON.
secsvc audit verify --dir Walks the whole chain with no grant.
secsvc audit anchor --dir Anchors a single-file chain from before audit.head, once, with the daemon stopped.
secsvc audit migrate --dir Moves a single-file chain into segments, once, with the daemon stopped.

call verbs and the routes they reach:

verb request
status GET /v1/status
catalog GET /v1/catalog
config GET /v1/config
findings GET /v1/findings
modules GET /v1/modules
report GET /v1/report
audit GET /v1/audit
verify GET /v1/audit/verify
scan POST /v1/scan
baseline POST /v1/baseline
contact PUT /v1/contact, body from --contact-file
config-set PUT /v1/config, body from --file

GET /v1/audit/head and POST /v1/audit/witness have no call verb; the off-host collector that uses them, in the SystemAPI agent and control plane, is built on systemapi.io main and not yet deployed.

Breaking changes

Both hardening batches are on the default branch. Each fix in them came with a test that fails when it is reverted and a stable refusal code. The full contracts, with the decisions made during the build, are hardening batch 1 and hardening batch 2.

Hardening batch 1

  • Grants are secsvc/2 with a signed iat. secsvc/1 grants are refused (grant_bad_shape); re-sign them with this binary's secsvc grant.
  • --host must be a real host name. Empty, localhost and the other loopback names, and IP literals are host_unset. Set it in the unit, service.env, or conf.d/secsvc.
  • An existing audit chain has no audit.head and is now audit_truncated. Run secsvc audit anchor --dir /var/lib/secsvc once, with the daemon stopped, then start it.
  • A version-1 integrity baseline is not used. Every watched path reports unbaselined until you re-baseline with secsvc call baseline and a security.baseline grant.
  • listen_allow and the auth thresholds need grant coverage of what they govern (config_scope otherwise), and POST /v1/scan spends its lease.

Hardening batch 2

  • The audit chain is segmented under audit/. A state directory with audit.jsonl is refused with audit_layout; with the daemon stopped, run secsvc audit migrate --dir /var/lib/secsvc (run secsvc audit anchor first if it reports audit_truncated on a chain from before audit.head).
  • GET /v1/audit?limit=N returns rows from the newest segment only; use GET /v1/audit/verify or secsvc audit verify for the whole chain.
  • GET /v1/audit/verify runs one walk at a time and once a minute per grant actor (429 rate_limited); poll the cheaper GET /v1/status instead.
  • Page bodies no longer name the host, a path, a subject, or an address; look a page's ref up in secsvc call findings (page_id), or set page_detail: true in the config to restore the old bodies.
  • Audit actions notify.sent, notify.failed and notify.coalesced are now page.sent, page.failed and page.coalesced; update anything that filters the audit by action.
  • Posting a witness needs the new purpose security:witness (ceiling security.audit, security.witness); no other purpose carries it, so issue the collector secsvc grant --purpose security:witness.
  • audit_keep_segments and page_detail changes need a grant whose --watch covers the state directory (config_scope otherwise); issue the grant with --watch /var/lib/secsvc.

Startup

secsvc serve requires --dir, --pub, --host, and --socket. --interval defaults to 30s and must be at least 5s. A shorter interval returns usage before the state directory exists.

Order after that check:

  1. A --host that names no machine is host_unset, before the state directory exists: empty, localhost, localhost.localdomain, ip6-localhost, ip6-loopback, localhost6, localhost6.localdomain6, any name under .localhost, or an IP literal. Names are not resolved. Then host grammar, then load the public key. Log step validate.
  2. Open the state directory at mode 0700. Log step store.
  3. Listen on the absolute socket path. Log step listen.
  4. chmod the socket to 0660.
  5. Write one byte, \n, to the file descriptor in SAHINIT_READY_FD when that variable is set. The descriptor number is the variable's value. Log step ready.
  6. Start the scan loop, then serve HTTP until SIGINT or SIGTERM.

The ready byte is written only after Listen succeeds. A clean shutdown unlinks the socket and returns success.

The parent of the socket is created at mode 0750 when it is missing. An existing socket inode is removed and replaced. A symlink at the socket path or its parent is bad_socket.

Grant

Domain string secsvc-grant-v2\n. The signed fields are v, actor, host, purpose, iat, exp, lease_id, entitlements, and watch; all are required. Signature is Ed25519 and is checked before a star, a filesystem root, expiry, iat, TTL, the purpose ceiling, and the host. Maximum document size is 16 KiB. Maximum TTL is 900 seconds. An iat more than 60 seconds ahead of the daemon clock is grant_future (401). exp - iat above 900 seconds, or exp not after iat, is grant_ttl, so a grant cut far into the future never becomes usable in its last minutes. A secsvc/1 grant, which has no iat, is grant_bad_shape; reissue it with this binary's secsvc grant, which signs iat as the current time. A lease id matches ^[A-Za-z0-9_-]{8,64}$.

purpose ceiling
security:read security.audit, security.read
security:config those, plus security.baseline, security.config, security.notify
security:operate those, plus security.scan
security:witness security.audit, security.witness

security.witness is a write, so only the security:witness purpose carries it: a read, config, or operate grant cannot post a witness (asking for it is grant_purpose). The witnessing party gets a security:witness grant.

* is grant_star. A watch of / is grant_root_slash. The daemon refuses a grant whose host differs from --host with grant_host. A second use of the same lease id is grant_spent. Spend is recorded before the commit and stays recorded when the commit fails. A blocked ntfy egress check returns before the lease is spent.

A grant's watch list covers an auth_log or watch path that a config replace adds or removes. An unchanged path may sit outside the grant; an uncovered changed path is forbidden. listen_allow entries are addresses, not paths.

Global fields need coverage of what they govern, so a grant scoped to one path cannot change them. A listen_allow change (as a set) needs a grant that covers /proc/net/tcp and /proc/net/tcp6, for example --watch /proc/net. An auth_fail_limit or auth_window_s change needs coverage of every auth_log set before or after the replace, and is refused when neither is set. Otherwise the replace is config_scope (403) and spends nothing.

HTTP

Header X-Secsvc-Grant. One value. Body cap 64 KiB. Header cap 32 KiB. Read header timeout 5s, read and write timeouts 10s. The write timeout is a tested guarantee for scans: a scan answers once its findings are committed and pages afterwards (see IDS), so a slow ntfy never holds the response. Unknown paths return 404 {"error":"bad_path"} before the grant is read. A known path with the wrong method returns 405 before the grant is read. A grant that lacks the route entitlement is 403 forbidden before the body is parsed.

method path entitlement
GET /v1/audit security.audit
GET /v1/audit/head security.audit
GET /v1/audit/verify security.audit
POST /v1/audit/witness security.witness
POST /v1/baseline security.baseline
GET /v1/catalog security.read
GET /v1/config security.read
PUT /v1/config security.config
PUT /v1/contact security.notify
GET /v1/findings security.read
GET /v1/modules security.read
GET /v1/report security.read
POST /v1/scan security.scan
GET /v1/status security.read

POST /v1/scan and POST /v1/baseline require an empty body. Both spend the grant's lease, so a second scan on the same grant is grant_spent. The internal scan loop spends nothing. PUT /v1/config replaces the whole config. {} is a valid replace and clears auth_log, watch, and listen_allow. GET /v1/audit that fails chain verification returns 500 audit_bad. GET /v1/audit?limit=N returns the last N rows of the newest segment only, so just after a segment rolls it returns fewer than N. GET /v1/audit/verify is the full walk of every segment. One walk runs at a time, and each grant actor gets one walk a minute; any other call is 429 rate_limited at once, before anything is read. POST /v1/audit/witness spends its lease. Audit JSON uses the API field names seq, prev, time, actor, lease_id, action, detail, hash.

GET /v1/status also carries anchor_pub, the hex Ed25519 public key that signs audit heads (see Audit), and the config view carries audit_keep_segments and page_detail.

Capabilities

GET /v1/status includes caps. Each entry is a name from a fixed registry, a state of ok, degraded, or absent, and a reason from a closed set. ok has an empty reason. The registry is audit, auth, grant_v1, integrity, listen, and notify.

reason when
flag_off the detector is not configured
target_missing the auth log is absent, or any watched path is absent
unbaselined a watched path has no baseline record
no_key grant_v1: no grant public key is loaded
unreadable a target is not a readable regular file, or the listener table is oversized
unsupported_os this host has no listener table
audit_bad the hash chain does not verify
bad_contact a stored contact does not parse
probe_error any other probe failure

grant_v1 is ok only when the daemon holds a loaded public key, and absent with no_key otherwise (the name is kept for the registry; the format it verifies is now secsvc/2). integrity is ok only when every watched path is a readable regular file with a baseline record; otherwise it is degraded with unreadable, then target_missing, then unbaselined, the worst first. Status never claims coverage it lacks. A probe is read-only. It does not follow a symlink and it does not read file contents. The report carries no path, contact, listener address, or error string. A result does not grant: GET /v1/status still requires security.read, and a degraded capability leaves every other route on its own entitlement. GET /v1/catalog remains the route and entitlement list.

The Unix client sets Transport.Proxy to notify.NoProxy, a function that returns no proxy. Go treats a nil Proxy as ProxyFromEnvironment, which would honor HTTPS_PROXY and could observe the request. The client does not clone http.DefaultTransport.

State directory

Mode 0700. Files are mode 0600.

file contents
config.json auth_log, auth_fail_limit, auth_window_s, watch, listen_allow, modules, audit_keep_segments, page_detail
contact the ntfy contact string
baseline.json {"v":2,"records":{...}}: per watched path, SHA-256, size, full mode, uid, gid
ids-state.json auth position (path, inode, device, offset), open findings, coalesce times, last scan
spent.json lease id to expiry
audit/NNNNNN.jsonl hash chain segments, mode 0600 in a 0700 directory
audit/segments.json index of closed segments: first seq, last seq, last hash
audit.head anchor: last seq and hash of the chain
anchor.key Ed25519 seed that signs audit heads; created once with O_EXCL; never printed
witness.jsonl witness records an off-host party posted and the chain held, newest last; before an append it is compacted to at most 500 in at most 64 KiB when it would reach 1000 lines or 128 KiB (half the room to the highest seqs, so the highest-seq witness is always kept, the rest to the newest arrivals, in arrival order), so it stays far below its 256 KiB read cap
audit.jsonl.migrated the single-file chain after secsvc audit migrate, kept for the operator
lock POSIX record lock held by the daemon for its lifetime
findings.jsonl capped edge log, 500 lines or 1 MiB

GET /v1/config returns contact_sha256 and contact_state. The contact URL is not a response field and is not an audit field.

Audit

Each row's hash is SHA-256 over the canonical JSON of seq, prev, time, actor, lease_id, action, and detail. The first prev is 64 zero hex digits. A rewritten, reordered, truncated, or extra-field line fails verification. A symlink is not followed. A failed append marks the chain broken so later appends fail closed. secsvc audit verify --dir DIR runs the full walk with no grant. A missing chain with no anchor verifies as zero rows.

Segments. Rows go to audit/NNNNNN.jsonl, numbered from 000001. A segment holds at most 20,000 rows or 4 MiB; the row that would pass either cap goes to the next segment. The hash chain runs across segments: the first row of segment N has prev equal to the last hash of segment N-1. Closing a segment writes its entry to audit/segments.json (temp file, fsync, rename, directory fsync) before the next segment's first row, so a crash between them leaves a closed index and no next segment, which opens and continues. A segment past the one the index leaves open, or an index whose last entry does not link to the newest segment, is audit_bad.

Runtime reads. Status, GET /v1/audit, and GET /v1/audit/head read only audit.head, audit/segments.json, the newest segment (capped at 4 MiB), and witness.jsonl; an append reads nothing and writes the row, the anchor, and on a roll the index. The running daemon is the only writer, so the index must equal the one it holds in memory and the newest segment must end at the row it last wrote; otherwise audit_truncated. A runtime read does not open old segments, so it does not see a rewritten or deleted old segment.

Full verify. secsvc audit verify and GET /v1/audit/verify walk every segment on disk, one line at a time with a buffer of one line (64 KiB), against the index: each closed segment must start at its entry's first seq, link to the previous entry's hash, and end at its own entry's last seq and hash; otherwise audit_bad. A missing segment is audit_truncated unless the newest audit.pruned row covers it (see Retention). This is the check that catches a rewritten old segment. In the daemon it takes neither the engine lock nor the store lock: the chain snapshots the index, the newest segment, and the witnesses under its own lock, then walks the closed segments, which do not change, without it, so scans and appends go on. A prune that lands during a walk appends its audit.pruned row but leaves the files until the walk ends, and the end of the walk deletes them. A stored witness the chain no longer holds fails the walk with audit_truncated, and secsvc audit verify prints witness seq N on a second stderr line.

Retention. audit_keep_segments in the config (default 0, keep all; at most 1,000,000) keeps that many closed segments. When a segment closes and more are kept than allowed, the daemon first appends audit.pruned with from, through (segment numbers), and the last_seq and hash of segment through, then deletes those files. The index keeps every entry, so the oldest retained segment stays linked. The full verify accepts missing segments only up to the newest audit.pruned row's through, and only when that row's last_seq and hash equal the index entry; a file a failed delete left behind still verifies, and the next roll retries the delete. Changing audit_keep_segments (or page_detail) needs a grant whose watch covers the state directory, otherwise config_scope, because it deletes audit history.

Layout and migration. A state directory with audit.jsonl is the old single-file layout: open, the daemon, and verify refuse it with audit_layout. secsvc audit migrate --dir DIR holds the store lock (store_busy under a daemon), verifies the old file line by line against audit.head exactly as batch 1 did (a non-empty chain with no anchor is audit_truncated: run secsvc audit anchor first), writes the segments and index into a temporary directory, renames it to audit/, renames the old file to audit.jsonl.migrated, and appends audit.migrated with the seq, hash, and segment count. An existing audit/ is audit_layout. A crash between the two renames leaves both, and open, verify, and migrate refuse with audit_layout: move audit.jsonl aside by hand, then run secsvc audit verify (that chain has no audit.migrated row). secsvc audit anchor works only on the single-file layout.

audit.head holds seq and hash of the last row, wherever its segment. It is created with the first row, written atomically after each append (temp file, fsync, rename, directory fsync), and read before the chain. Open, verify, and every runtime re-read (status, GET /v1/audit) return audit_truncated when the chain ends before the anchor's seq, when the row at that seq has a different hash, when the chain is more than one row past the anchor, when the chain is missing or empty while the anchor exists, or when a non-empty chain has no anchor. An anchor exactly one row behind (a crash between the row and the anchor) is moved up on open. A running daemon also checks that the row it last wrote is still on disk with the same hash, so deleting the anchor and truncating the chain under it is audit_truncated too.

A chain written before anchors existed is anchored once by the operator: secsvc audit anchor --dir DIR verifies the whole chain, writes the anchor, and appends audit.anchor_init with the seq and hash it anchored. It holds the store lock (lock, a POSIX record lock that serve takes for its lifetime), so it refuses with store_busy while a daemon owns the directory, and refuses with anchor_exists when an anchor is already there.

Residual: the anchor is local. Root, or anyone who can write the state directory, can rewrite or delete every file together while the daemon is stopped. The anchor stops a truncation of the chain alone, not an attacker with the directory. The off-host anchor below is what catches that; its agent side is built on systemapi.io main, not yet deployed.

Off-host anchor (secsvc side)

anchor.key is an Ed25519 seed that serve creates in the state directory at the first start (O_EXCL|O_NOFOLLOW, mode 0600, fsynced). It is never printed or returned; a group- or world-readable key is seed_perms at startup. Its public key is anchor_pub in GET /v1/status. It is a different key from the grant key.

GET /v1/audit/head (security.audit) runs the runtime check, then returns {"head":{"host","seq","hash","segment","time"},"sig"}. sig is base64 Ed25519 over the bytes secsvc-audit-head-v1\n followed by the compact JSON of head in that field order. The domain line keeps a head signature from being valid as anything else. An empty chain has seq 0, the genesis hash, and segment 0. The response does not carry the public key: a verifier pins anchor_pub out of band, once.

POST /v1/audit/witness (security.witness, spends the lease) takes a strict body {"seq","hash","witness","time"}: seq at least 1, hash 64 lowercase hex, witness matching ^[A-Za-z0-9:._@/-]{1,128}$, time RFC 3339 and at most 35 characters. Anything else is bad_path. secsvc stores a witness only when the chain holds it now: the row at seq exists and has that hash. Then it appends the witness to witness.jsonl and audits audit.witness. A seq past the end or another hash is witness_mismatch (409). A row inside a pruned segment, other than that segment's last row (whose hash the index keeps), is witness_unverifiable (409). A refused witness is not stored and does not break the chain; it is audited as audit.witness_refused with the actor and lease of the verified grant, the witness record, and the code, so a bad poster is traceable. The witness label is the poster's data, not an identity. A witness that was stored and later stops matching is tampering with the chain: the runtime read (newest witness, which must also be the one the daemon last stored), open, and the full verify (every stored witness) report audit_truncated, fail closed across restarts. The operator investigates with secsvc audit verify, which names the witness's seq. Root can delete witness.jsonl with everything else; the protection is the copy the witnessing party keeps.

IDS

Three detectors, off until configured.

Auth tail reads auth_log from a stored position: path, inode, device, and offset. A different inode or device, or a size below the offset, is rotation and restarts at 0, so a new file that grew past the old offset is still read. Copytruncate rotation keeps the inode: lines written after the copy and past the saved offset before the next scan are missed, because the file only looks rotated once its size drops below the offset. Prefer create-mode rotation (logrotate's default) for the auth log. The first scan of a path with no saved position for it (a new install, a changed auth_log, or state from an older binary) starts at the end of the file and pages on nothing, because old lines would otherwise be dated now. The IP in the summary comes only from sshd's fixed structure, the token after the last from that precedes the last port, and must parse as an IP; otherwise the summary has no IP. PAM rhost= is not read. Matching is a fixed substring list. The raw line is not a finding. Five failures in 300 seconds is the default, and the finding is auth_fail at severity high. An unreadable log suppresses auth_fail for that scan and records auth_log_unavailable at medium.

Integrity Lstats each watch path and does not follow a symlink. A symlink, a missing baselined path, a changed hash or size, a changed mode (file type, setuid, setgid, sticky, or permission bits), uid, or gid, or an unreadable baselined file is high. A version-1 baseline (a bare path map, permission bits only) is neither compared nor upgraded, because adopting the file's current setuid bit, uid, or gid would bless a change made before the upgrade: it loads as no records, every watched path is integrity_unbaselined and the integrity cap is unbaselined, until an explicit POST /v1/baseline writes version 2 with its baseline.set audit row. A missing or unloadable baseline never resolves an integrity finding: an open integrity_changed, integrity_missing, integrity_symlink, integrity_not_file, or integrity_oversize on a watched path with no baseline record stays open at its severity until a scan against a real baseline shows the file matching, or the path leaves the watch list. An unbaselined path is medium. POST /v1/baseline measures the current watch list. Every open of a configured path, by a scan or by the status probe, is O_NONBLOCK|O_NOFOLLOW and checks with fstat that the file is regular before any read; a FIFO, socket, or device is integrity_not_file (or auth_log_unavailable, or a capability unreadable) with internal code not_regular, never a blocking read. Reads are capped (1 MiB per auth scan, 4 MiB per hashed file).

Listeners decode /proc/net/tcp and /proc/net/tcp6 only when listen_allow is non-empty. An address outside that list is listen_unexpected at high. A truncated table is listen_truncated at medium. A decode failure is unsupported, so a partial table is not treated as clean.

Only severity high is paged. A medium finding is audited and marked paged immediately, so it does not page on a later scan. The same kind pages at most once per 60 seconds (page.coalesced). With no contact file, paging is off and the finding is still marked paged.

Pages are sent after the scan commits. A scan decides its pages, marks each finding pending (durably, in ids-state.json with the scan's commit), and queues the pages on a bounded queue (64); the response returns then. A pager goroutine sends each page (5 s timeout) and audits page.sent or page.failed with the kind, the contact fingerprint, the page id, and the error code. A finding becomes paged only on page.sent. A failed send or a full queue (queue_full) clears pending and leaves the finding unpaged, so the next scan pages it again. A bad contact at decision time is page.failed in the scan itself. At shutdown serve stops the scan loop first and the pager after it; pages still queued stay pending, and at the next start serve queues every pending page again before the first scan, so neither a stop nor a crash between the commit and the send loses a page (a crash during a send may send it twice).

Pages carry no host detail. The ntfy topic is public to anyone who learns or guesses it, so treat the contact as a secret and the page as public. By default a body is

  • secsvc high KIND: N high finding(s) open, ref PAGEID

where KIND is the finding kind, N the number of open high findings after the scan, and PAGEID 16 random hex characters stored with the finding. It names no host, path, subject, summary, or address. secsvc call findings (and the report) shows page_id next to the local detail. page_detail: true in the config restores the old bodies, clipped at 200 bytes on a UTF-8 boundary, and puts that detail on the public topic:

  • secsvc auth_fail on HOST: SUMMARY
  • secsvc integrity_changed on HOST: SUBJECT
  • secsvc listen_unexpected on HOST: SUBJECT

The contact form is the same string notices.js accepts: push:ntfy:https://ntfy.sh/ plus a topic of 20 to 64 characters from [A-Za-z0-9_-]. Email, another host, userinfo, a port, a query, a fragment, and a trailing slash are bad_contact.

ntfy

http.Transport.Proxy is notify.NoProxy. TLS minimum version is 1.3. ServerName is ntfy.sh. Redirects are refused. The client timeout is 5 seconds. DNS answers are pinned to public addresses; any loopback, private, link-local, CGNAT, multicast, unspecified, documentation, or benchmarking address, including 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, and 2001:db8::/32, is blocked_address. There is no allow-private switch. A response is success only for status 2xx. Logs and audit rows store the contact's SHA-256, never the topic.

PUT /v1/contact parses, checks egress, then spends the lease.

Fail closed

A bad grant, a bad path, a bad contact, a blocked address, a broken audit chain, and a failed spend return an error and leave the previous state in place. The scan loop does not save detector memory when the audit append fails, so the next scan retries the page. Socket mode is not authentication. The process logs stable codes and does not log seeds, grant documents, or contact URLs.

Module results and report snapshots

See Distro security modules for the module registry, fixed read surfaces, authorization, coverage states, and the secsvc-report/1 contract. Module results and detector-config fingerprints are persisted with ids-state.json. Explicitly disabling a module/check writes ids.withdrawn for removed findings; incomplete checks retain prior findings. Status includes system and config_changed; the original capability registry remains unchanged.

OpenRec now stores first/last seen times and whether a finding was observed in the last scan. Old state without these additive fields remains readable. Older binaries use strict state parsing, so downgrade requires an explicit state migration/backup plan; do not overwrite the new state with an older binary.

Distro security modules

secsvc now has six compiled-in, read-only distro modules. Configuration can enable several profiles for a fleet, but only the profile matching the machine's exact /etc/os-release ID runs. Unknown distributions are reported as unsupported; ID_LIKE is not a claim of validated support. No package installation, shell commands, automatic remediation, or network requests are performed by these checks.

Config key OS ID Package ecosystem (metadata only) Default MAC check
debian debian apt AppArmor
ubuntu ubuntu apt AppArmor
redhat rhel dnf SELinux
rocky rocky dnf SELinux
alpine alpine apk none
arch arch pacman none

Each profile defaults to accounts, permissions, kernel, ssh, and mounts. Debian, Ubuntu, Red Hat, and Rocky also default to mac. A distribution's MAC choice is a profile policy, not proof that the feature is installed. Missing or unreadable MAC interfaces make coverage degraded. Alpine/Arch can explicitly select mac, but it reports unsupported until a policy is implemented for them.

Module configuration

Existing configurations remain valid, and modules default off. Example:

{
  "modules": {
    "ubuntu": {"enabled": true, "checks": ["accounts", "permissions", "kernel", "mac"]},
    "rocky": {"enabled": true},
    "alpine": {"enabled": false}
  }
}

Omitted or null checks means the profile defaults; checks: [] means no checks. Unknown profiles, unknown checks, duplicates, and unknown object fields are rejected. PUT /v1/config remains a full replacement, so retain any existing auth_log, watch, and listen_allow entries you want to keep. {} disables all detectors. See examples/ for per-distro and fleet configurations.

Enabling or disabling a profile/check requires security.config and grant watch coverage for its fixed input paths. Checks that do not change need no additional coverage. Discovery paths /etc/os-release and /usr/lib/os-release are required for changes, even when configuring a profile for a different distro. This prevents an automatic future match from introducing unauthorized reads.

For example, using an existing signing seed and a daemon configured as host1:

secsvc grant --seed /etc/secsvc/seed --actor ops --host host1 \
  --purpose security:config --ttl 10m --lease module-config-0001 \
  --watch /etc --watch /usr/lib/os-release --watch /proc/sys \
  --watch /proc/1/mountinfo --watch /sys > /tmp/module-grant.json
secsvc call config-set --socket /run/secsvc/sock \
  --grant /tmp/module-grant.json --file examples/fleet.json

The default scan loop applies the config on its next scan. Use a separate grant with security.scan to request an immediate scan. Read grants can inspect:

secsvc call modules --socket /run/secsvc/sock --grant /tmp/read-grant.json
secsvc call report --socket /run/secsvc/sock --grant /tmp/read-grant.json
secsvc call status --socket /run/secsvc/sock --grant /tmp/read-grant.json

GET /v1/modules returns the registry; GET /v1/report returns a coherent local snapshot with schema secsvc-report/1. Both require security.read. GETs do not run system checks. The existing /v1/catalog and call catalog expose routes.

Checks and limits

Check Inputs and findings
accounts /etc/passwd, /etc/shadow: non-root UID-zero accounts, duplicate UIDs, empty password fields. Findings contain counts, never usernames or password hashes. Locked password markers are not empty passwords. This covers local files, not LDAP/NSS identities or PAM's effective login policy.
permissions Root ownership and excessive permissions on passwd, group, shadow, gshadow, sudoers, and sshd_config. Shadow group-read is allowed; group-write and other access are flagged. The group of shadow and gshadow must be root, or on Debian, Ubuntu, and Alpine the shadow group as named in /etc/group; any other group is a high group finding, and an unreadable or malformed /etc/group makes the check incomplete. Red Hat, Rocky, and Arch allow root only. Missing optional files still produce degraded coverage. Symlinks are not followed.
kernel Twelve live /proc/sys values: ASLR, kernel pointer/log restrictions, protected hardlinks/symlinks, IPv4 redirect/source-route settings and SYN cookies. Findings are policy observations, not proof of exploitation. Per-interface and IPv6 policy are not evaluated.
ssh Explicit risky global declarations in /etc/ssh/sshd_config, with first-value semantics. Includes, Match blocks, quoting, continuations, and nontrivial syntax mark coverage incomplete. Match-specific settings are not evaluated; defaults are not inferred. This does not claim to reproduce sshd -T or prove the running daemon uses this file.
mounts /proc/1/mountinfo: nosuid and nodev on dedicated /tmp, /var/tmp, /dev/shm mounts. Missing dedicated mounts are review findings. Parent/inherited protections are not guessed. A container PID 1 describes that container's namespace, not its physical host.
mac Red Hat/Rocky: /sys/fs/selinux/enforce, with permissive mode flagged high. Debian/Ubuntu: AppArmor enablement and loaded enforcing/complain profile counts. Missing interfaces mean unknown coverage, not an assertion that MAC is disabled. Loaded profiles do not prove every workload is confined.

Reads are limited to 1 MiB per fixed input; special files and final-component symlinks are rejected without blocking on FIFOs. The only permitted final symlink is /etc/os-release pointing to the fixed /usr/lib/os-release target. Parent directory symlink handling follows the existing service threat model (out of scope). Modules do not follow configurable paths, run subprocesses, or emit raw host file contents. security.read still exposes finding subjects (paths) and existing IDS summaries; do not treat the report as anonymous telemetry.

Coverage and finding lifecycle

Module/check states: disabled, pending, not_applicable, ok, degraded. Platform detection additionally uses absent for unsupported OS/distro. ok means the check completed; a completed check may have high findings. Reasons are fixed codes, never error strings. Empty findings with degraded, disabled, pending, or mismatched coverage do not mean the machine is secure.

Findings use kinds system.<profile>.<check>.<rule>. They join the existing open finding set, audit edges, and high-severity ntfy flow. A failed/incomplete check retains previous findings; successful checks can resolve them. Disabling a check removes its findings with an ids.withdrawn audit edge rather than ids.resolved. A distro change retains the old profile's findings until that profile is explicitly disabled. New observations update last-seen timestamps.

Reports include stable finding IDs, first/last seen times, and an observation of observed, retained, or stale. A fingerprint hashes host + NUL + kind + NUL + subject (the existing auth finding identity is just its kind). Missing historical timestamps are empty for records written by older binaries; they are not invented.

last_scan is the last completed persisted scan. generated_at is only the response time. config_sha256 identifies current normalized detector config; scan_config_sha256 identifies what was scanned. A difference sets config_changed, makes coverage pending, and marks findings stale until a scan completes. Contact changes do not change this detector-config fingerprint.

This release does not add remote reporting, package/CVE scanning, firewall rule evaluation, malware signatures, compliance certification, or automatic repairs. Those need their own bounded collectors, policies, and validation. The local module interface and report contract are the foundation for that work.

Module validation

Fixture tests exercise all six exact distro IDs, positive and negative checks, unsupported platforms, partial failures, path authorization, redaction, symlinks, FIFOs, read limits, finding retention/withdrawal, API access, and restart behavior. Run go test -count=1 -race ./... and go vet ./.... Linux amd64/arm64 builds can be produced with CGO_ENABLED=0 GOOS=linux GOARCH=... go build ./cmd/secsvc. Container smoke tests also passed on Debian 12, Ubuntu 24.04, Rocky 9.8, and Alpine 3.20.10 using the locally cached images. The Alpine root filesystem image was ARM64 while the static test executable and Docker host were AMD64; this tests Alpine's files/interfaces, not a native ARM64 execution environment. Each container correctly reported degraded coverage for missing host interfaces/files.

Run scripts/test-distros.sh debian ubuntu rocky alpine to repeat those tests. With no arguments the script also includes Red Hat UBI and Arch; it uses --pull=never, so provision those images first. Containers have no network, read-only roots, a temporary /tmp, and only the test executable mounted read-only. Red Hat and Arch currently have fixture coverage, not container validation here. Service-manager integration and real distro/kernel combinations still need native host testing; container tests and cross-compilation are not that validation.

Module references

The sash verb (planned)

This section is the contract for a later sash builtin. The sash table in skills/sash/reference/verbs.md does not contain these names, and this repository does not edit that table. Fulfillment, when it exists, is one secsvc call against the host Unix socket. The grant on that call is secsvc/2, described under Grant. A sash/1 lease does not authorize the socket.

Columns match the sash verb table. key is the secsvc/2 entitlement. mutates is yes when the call spends a lease.

form kind key mutates what
security status verb security.read no GET /v1/status, including caps.
security config verb security.read no GET /v1/config. The body has contact_sha256, never the contact URL.
security findings verb security.read no GET /v1/findings.
security audit verb security.audit no GET /v1/audit.
security verify verb security.audit no GET /v1/audit/verify.
security scan verb security.scan yes POST /v1/scan with an empty body.
security baseline verb security.baseline yes POST /v1/baseline with an empty body.
security config set verb security.config yes PUT /v1/config, a full replace. Paths added or removed must sit under the grant watch list. listen_allow and the auth thresholds need coverage of what they govern (config_scope otherwise; see Grant).
security contact verb security.notify yes PUT /v1/contact. The contact file is mode 0600 and uses the push:ntfy:https://ntfy.sh/<topic> form.

security catalog is the same key as security status (GET /v1/catalog) and is optional in the first sash cut. caps on security status is a name, a state (ok, degraded, absent), and a closed reason. The list does not grant.

A star entitlement, a watch of /, a TTL over 15 minutes, and a host other than the daemon --host stay refusals. The agent re-checks the key. Plan mode stops the four mutating forms. Confirm asks before them.

Until that builtin exists, the operator runs secsvc call directly. See Operator quick start.

Built from the systemapi-security repository's README.md, docs/architecture.md, docs/modules.md, docs/sash-verb.md, packaging/README.md and units/secsvc.json, and the command-line table from internal/cli/cli.go, at commit e5d69c8 on branch main. Both hardening batches are on that branch. The repository has no license file yet.