Backport the applicable runtime bugs from develop #644, #646 and #660.
Raise small platform worker stacks while preserving larger defaults and
rejecting overflowing buffer configurations. Serialize SNMP session
construction, cleanup and every SNMPv3 request process-wide while v1 and
v2c requests stay parallel. Net-SNMP's README.thread says SNMPv3 support
was never checked for multi-threading correctness. One unresponsive v3
agent now delays other v3 polls by up to timeout x (retries + 1);
narrowing the lock needs the asynchronous API and is a develop-only
follow-up. Reject unavailable PHP reader slots and invalid host/thread
CLI numbers before indexing or sizing state. Consume overlong config
lines once, parse final lines without a newline, and keep config values
out of warnings.
Merge after #661. This keeps the flat maintenance sources and existing
runtime interfaces; no new dependencies or CI gates. Release notes will
be collected in the final maintenance PR.
Validation: native build and version smoke test pass through mise.
ASan/UBSan contracts exercise worker-stack defaults and errors,
active-session SNMP locking, and physical config-line boundaries. A
probe linked to the maintenance production objects passes five
script-output boundaries and three unavailable PHP slot cases. Seven
invalid numeric CLI invocations fail before config/database access. The
critical flawfinder gate passes. No live database or device was
contacted.
---------
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Consecutive SNMP items with the same credentials can target different
hostnames or require different timeouts. Include hostname and timeout in
the batch key so each endpoint gets its own session. External scripts
also read one byte less than the allocated buffer, which makes a full
truncated response indistinguishable from a complete value. Read the
full capacity once and return U for a full buffer or embedded NUL.
Uptimes must be whole unsigned counters. Reject decimal, negative and
overflowing responses and check seconds-to-centiseconds conversion
before multiplication. Invalid values cannot advance reindex state.
Backports the confirmed bugs fixed in #641. Keeps the maintenance
branch’s single-read response contract, timeout handling and nonblocking
child reaping. Changes poller.c and extends the existing maintenance CI
branch filter to stacked fix branches. Release notes are collected in
#664.
Validation: native build and version smoke test passed through mise.
Compiled production hostname comparisons reject the old behavior and
pass with the fix. A probe linked to the maintenance production objects
passed short output, the maximum terminated value, overflow, embedded
NUL and a response whose child keeps stdout open; the last case returned
in under 0.5 seconds. The probe substitutes only semaphore boundaries
because macOS does not support the legacy unnamed semaphore
implementation. No database or live device was contacted. The modified
file passed the flawfinder critical gate.
Additional validation: the compiled maintenance timeout comparison fails
before the fix and passes afterward. Eleven production uptime parser
boundary cases pass under ASan/UBSan. The native build and all five
existing script-output probes still pass.
---------
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
## What
- `nft_pclose()` (`nft_popen.c`) no longer does an unbounded blocking
`waitpid(cur->pid, &pstat, 0)` after closing a script's pipe. It now
checks once (with a brief ~20ms allowance for normal fork/exec/exit
scheduling latency), kills anything still running, and hands it to a new
bounded abandoned-pid sweep (ported from develop's `nft_popen.c`)
instead of waiting on it. The sweep runs opportunistically at the top of
the next `nft_popen()` call, so nothing is reaped synchronously on the
polling thread.
- Removed the `USING_TPOPEN`/`--enable-popen` native-`popen()` fallback
in `exec_poll()` (`poller.c`, `configure.ac`). It could not track or
kill a timed-out child (no pid available from a real `popen()`), so a
timeout there could only ever abandon the descriptor without terminating
the process - noted as explicitly out of scope in #574.
`php_close()`'s existing reap logic
(`php_signal_servers`/`php_reap_servers`/`php_park_orphan`, added by
#574) was checked and is already bounded to roughly 200ms shared across
all configured script servers, not the multi-second-per-script blocking
pattern found on develop - no change needed there.
## Why
Investigating a reported poller slowdown found `nft_pclose()` could
block a poller thread indefinitely (until the child actually exited) for
any script whose process hadn't exited by the time its pipe was closed -
worse than develop's equivalent bug (#614), which was at least bounded
to ~5 seconds. Tracked in #632; design principles written up in #631.
## What was tested
This branch has no in-tree C test harness (per #574's own notes), so
validation was:
- `./bootstrap && ./configure --enable-warnings && make` - clean build,
no new warnings (two pre-existing, unrelated warnings in
`php.c`/`util.c`).
- `cppcheck --enable=all --std=c11` on `nft_popen.c`/`poller.c` - no new
errors.
- A standalone smoke harness (compiled against the built `nft_popen.o`
with local stubs for `spine_log()`/`thread_mutex_lock()`, not committed)
exercising `nft_pclose()` against a fast-exiting `nft_popen()` child and
a lingering one:
- Fast child ("exit 7"): reaped with the real exit status (`WIFEXITED` /
`WEXITSTATUS(7)`).
- Lingering child (prints then loops forever): `nft_pclose()` returned
in ~0.029s instead of blocking, logged the "parked for reaping" warning,
and was confirmed swept/reaped by a subsequent `nft_popen()` call with
`ps` showing no leftover zombie.
---------
Signed-off-by: TheWitness <thewitness@cacti.net>
## What
Adds `.github/instructions/instructions.md` (did not exist on this
branch) with a *Script and process execution design principles (do not
regress)* section codifying three invariants for script and PHP Script
Server execution:
1. One read attempt per command, no looping to EOF.
2. Never block the polling thread in `waitpid()` — single non-blocking
WNOHANG attempt, then hand off to an async sweep.
3. Script timeouts must go through `nft_popen()`/`nft_pchild()`
(pid-tracked), not a native `popen()`/`pclose()` fallback.
## Why
While investigating a reported poller slowdown, this branch's
`nft_pclose()` was found to do an unbounded blocking `waitpid()` on the
polling hot path. Writing these invariants down so future AI-assisted
changes to this branch don't reintroduce that or the related issues
found on develop (#614). Tracked in #632.
## What was tested
Docs-only change; no build/test impact.
Signed-off-by: TheWitness <thewitness@cacti.net>
## Problem
`config_DATA = spine.conf.dist` only ever installs `spine.conf.dist`
itself under `$(sysconfdir)` (`/usr/local/spine/etc` by default).
Nothing produces a live `spine.conf`, so a fresh install has no usable
configuration until an operator manually copies the `.dist` file.
## Fix
Added an `install-data-hook` that copies `spine.conf.dist` to
`spine.conf` under `$(configdir)`, but only when `spine.conf` does not
already exist. A first install seeds a working config; a re-install
(upgrade in place) never touches an already-customized `spine.conf`.
## Testing
Verified via WSL:
- Fresh `make install DESTDIR=...` creates `etc/spine.conf` identical to
`spine.conf.dist`.
- Hand-edited `spine.conf` (appended a marker line) survives a second
`make install` unchanged.
## Summary
The 1.2.x-affected subset of a batch of small, independent, unaddressed
bugs from the open-issue backlog (the two develop-only issues from the
same audit, #583 and #580, are not applicable here — see the companion
PR for `develop`).
## Fixes
- **`poll_host()` skips `mysql_thread_end()` when the device row is
missing** — the early `return` on `num_rows != 1` released both DB
connections and freed six allocations, but never called
`mysql_thread_end()`, unlike the other two exit paths. Added the missing
call.
- **SNMPv3 passphrase scrubbing flag never set** — `zero_sensitive` was
a function-local initialized to 0 and never assigned, so every guarded
`memset()` was dead code. Made scrubbing of this module's own heap
copies (`Apsz`/`Xpsz`) unconditional. Left the caller's
`snmp_password`/`snmp_priv_passphrase` alone rather than also scrubbing
those in place — those are `host_t`-owned and get reused for later
session rebuilds against the same host, so zeroing them would have
broken subsequent polls.
- **`php_readpipe()` FD_SET without an FD_SETSIZE check** — `FD_SET()`
doesn't range-check, so a read descriptor at or above `FD_SETSIZE` (1024
on glibc) wrote past the end of the on-stack `fd_set`. Added a bounds
check that treats an out-of-range descriptor as a script-server failure
(mark undefined, close, restart) instead of calling `FD_SET`/`select()`
on it.
- **Signal handler never re-arms, so the second SIGPIPE kills the
poller** — every fatal signal reset itself to `SIG_DFL` and never
re-armed. That's the right idiom for a real fault (SIGSEGV and friends
re-execute and die with a core), but SIGPIPE is a routine, recurring
condition — a second one previously killed the whole poller. Re-arm only
SIGPIPE.
- **spine fails to link on Fedora: undefined reference to
`usmDESPrivProtocol`** — some distributions ship a `net-snmp-config.h`
that advertises DES as the default privacy protocol while the shipped
`libnetsnmp` doesn't export the symbol. Added an `AC_LINK_IFELSE` probe
for the actual symbol and guarded the fallback to use
`usmAESPrivProtocol` when it's absent.
## Testing
Full build via WSL (`./bootstrap && ./configure --enable-warnings &&
make`) produces the `spine` binary with no new warnings in `poller.c`,
`snmp.c`, `php.c`, or `error.c`. Confirmed the new `usmDESPrivProtocol`
configure probe correctly detects the missing symbol in this build
environment (which also lacks it) and takes the AES fallback path
without a link error.
Closes#594Closes#600Closes#605Closes#607Closes#575
Backports the memory-safety, process-lifecycle, and polling-correctness
fixes identified in the 1.2.x review.
Memory safety and resource handling:
- fix the `strncopy` one-byte overflow and keep its scan portable to
older Solaris
- reserve the `php_readpipe` terminator byte, enforce one aggregate
response/startup deadline, and recycle a server whose partial or
oversized response leaves unread protocol data
- keep log newline appends inside `flogmessage` and initialize the
buffer before `strftime`
- free settings-query results on missing rows and check allocation
results before dereference
- preserve allocation ownership when trimming recache command output
Process and privilege lifecycle:
- send quit to every PHP server before a shared grace period, then
signal/reap in parallel rounds with bounded SIGTERM-to-SIGKILL
escalation
- normalize `SIGCHLD` to `SIG_DFL`, verify retained children with
`waitpid` before signaling, and prevent active slots from overwriting
unreaped PIDs
- bound failed-server restart churn and make every no-server caller
return `U`
- block SIGPIPE only around complete script-server writes and consume
only a newly generated pending signal
- create pipe/socket descriptors close-on-exec, using
`pipe2`/`SOCK_CLOEXEC` when available and a serialized fallback
otherwise
- serialize `vfork`, optional libc `popen`, and the complete
process-wide euid-0 raw-socket window so data-input children cannot
inherit root
- remove unnecessary privilege elevation when closing raw sockets and
fail closed if privileges cannot be dropped
Polling correctness:
- preserve complete database hostnames, including bare IPv6 literals.
The removed host:port parser was dead: callers do not consume its
method/port outputs and overwrite those fields from the database, while
tokenizing the hostname truncated valid IPv6 input.
- validate IPv4 and ICMP header lengths before access, consume rejected
peeked datagrams, and correlate echo replies by host, type, identifier,
and sequence
- make `snmp_count` stop on internal Net-SNMP errors, distinguish SNMPv1
`noSuchName` walk completion, and avoid turning internal errors into
valid zero counts
- fail closed when device/item-count rows cannot be fetched, preventing
zero counts from becoming unbounded duplicate polls
- make CLI fatal paths return failure and guard nullable database row
fields
Verification:
- `./bootstrap` completes (using Homebrew `glibtoolize`; the initial
unavailable GNU `libtoolize` probe is non-fatal)
- default configure/build succeeds against Homebrew mysql-client,
net-snmp, and OpenSSL 3
- `--enable-popen` configure/build also succeeds
- both builds use `--enable-warnings` and `make -j4`; remaining warnings
are pre-existing macOS deprecations and unrelated unused variables
- `git diff --check` passes
- the blocking pre-push review gate passes all stages (critical/high,
secondary scanners, medium, and missing-test review)
Scope notes:
- The new close-on-exec handling covers descriptors created by the
changed PHP/script/ICMP paths. Existing MySQL, log, and Net-SNMP
descriptors do not yet have comprehensive close-on-exec coverage; that
broader descriptor audit should be a separate change rather than implied
by this backport.
- In the non-default `--enable-popen` mode, the existing timeout path
intentionally skips `pclose` and can retain a child until it exits. This
PR secures that mode's fork against the euid window but does not
redesign its legacy timeout ownership.
- Spine has no in-tree C test harness. The failure-mode paths were
statically reviewed and both supported build variants were compiled, but
deployment validation should still exercise PHP restart/orphan handling,
partial-response timeouts, SNMPv1 count behavior, and malformed/foreign
ICMP replies.
Closes#564Closes#565Closes#566Closes#573Closes#601Closes#604Closes#606Closes#608
---------
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Co-authored-by: TheWitness <thewitness@cacti.net>
## Problem
The uptime-goes-backward reindex check in `poll_host()` can source its
"current uptime" value from either of two OIDs:
- `.1.3.6.1.2.1.1.3.0` (legacy `sysUpTime`, centisecond granularity)
- `.1.3.6.1.6.3.10.2.1.3.0` (modern SNMP engine time, second
granularity)
Previously, every poll cycle unconditionally queried the legacy OID
first, then queried the engine OID and overwrote the value if it
answered numerically. A reindex row whose `arg1` was the engine OID
directly (with no legacy counterpart processed first in that cycle)
instead fell through to a plain, unconverted read of whatever `arg1`
was.
Because these two OIDs represent different underlying counters (device
uptime vs. SNMP engine uptime) on different scales, mixing which one
supplies the value for the comparison from cycle to cycle (or row to
row) can make the "current" value look smaller than the previously
stored one even though the device never rebooted, tripping the "uptime
went backward" assertion and triggering constant reindexing.
## Fix
Introduces a boolean, `uptime_use_engine_oid`, that records whether the
seconds-granularity engine OID (`.1.3.6.1.6.3.10.2.1.3.0`) answered with
numeric data for this poll. Once that's known:
- If present, the calculation is pinned to that OID (converted to
centiseconds so it stays comparable with historical values) for the rest
of the poll.
- Only when the engine OID is not present/numeric does the code fall
back to the legacy `sysUpTime` OID.
Both reindex rows that reference either OID now consistently resolve to
the same cached value within a poll, instead of potentially reading from
different sources.
## Testing
Compiled cleanly (via WSL) with no new warnings in `poller.c`. This is a
logic-only change to `poll_host()`; no build/config changes.
Closes: https://github.com/Cacti/spine/issues/622
The 1.2.x branch has no workflows, so PRs targeting it (e.g. #544's
crash/memory-safety fixes) get no build or analysis coverage. `ci.yml`
only exists on develop and only triggers there.
This ports develop's `ci.yml` to 1.2.x unchanged except the branch
filters: gcc + clang build matrix and flawfinder (critical-level gate).
Actions stay SHA-pinned.
Adding this lets #544 and future 1.2.x PRs build under both compilers
before merge.
---------
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Backports critical security fixes for Spine, including the elimination
of the sh -c wrapper in nft_popen and log redaction for sensitive
credentials. Addresses VULN-005 and VULN-013.
* TCP ping returns always Alive
* The Availability/Reachability setting of "Ping or SNMP Uptime" is not working in latest spine
* Update some logging functions to add the 'DEBUG' declaration.