Files
spine/error.c
T
Thomas VincentandTheWitness 4e1ded7e25 fix: memory-safety and polling correctness backports for 1.2.x (#574)
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 #564
Closes #565
Closes #566
Closes #573
Closes #601
Closes #604
Closes #606
Closes #608

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Co-authored-by: TheWitness <thewitness@cacti.net>
2026-09-22 09:07:45 -04:00

183 lines
6.1 KiB
C

/*
ex: set tabstop=4 shiftwidth=4 autoindent:
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2024 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU Lesser General Public |
| License as published by the Free Software Foundation; either |
| version 2.1 of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU Lesser General Public License for more details. |
| |
| You should have received a copy of the GNU Lesser General Public |
| License along with this library; if not, write to the Free Software |
| Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
| 02110-1301, USA |
| |
+-------------------------------------------------------------------------+
| spine: a backend data gatherer for cacti |
+-------------------------------------------------------------------------+
| This poller would not have been possible without: |
| - Larry Adams (current development and enhancements) |
| - Rivo Nurges (rrd support, mysql poller cache, misc functions) |
| - RTG (core poller code, pthreads, snmp, autoconf examples) |
| - Brady Alleman/Doug Warner (threading ideas, implimentation details) |
+-------------------------------------------------------------------------+
| - Cacti - http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
/* These functions handle simple singal handling functions for Spine. It was
written to handle specifically issues with the Solaris threading model in
version 2.8.
*/
#include "common.h"
#include "spine.h"
/*! \fn static void spine_signal_handler(int spine_signal)
* \brief interupts the os default signal handler as appropriate.
*
*/
static void spine_signal_handler(int spine_signal) {
signal(spine_signal, SIG_DFL);
set.exit_code = spine_signal;
/* variables for time display */
time_t nowbin;
struct tm now_time;
struct tm *now_ptr;
/* get time for poller_output table */
nowbin = time(&nowbin);
localtime_r(&nowbin,&now_time);
now_ptr = &now_time;
char *log_fmt = get_date_format();
char logtime[50];
strftime(logtime, 50, log_fmt, now_ptr);
switch (spine_signal) {
case SIGABRT:
fprintf(stderr, "%s FATAL: Spine Interrupted by Abort Signal\n", logtime);
break;
case SIGINT:
fprintf(stderr, "%s FATAL: Spine Interrupted by Console Operator\n", logtime);
break;
case SIGSEGV:
fprintf(stderr, "%s FATAL: Spine Encountered a Segmentation Fault\n", logtime);
exit(1);
break;
case SIGBUS:
fprintf(stderr, "%s FATAL: Spine Encountered a Bus Error\n", logtime);
break;
case SIGFPE:
fprintf(stderr, "%s FATAL: Spine Encountered a Floating Point Exception\n", logtime);
break;
case SIGQUIT:
fprintf(stderr, "%s FATAL: Spine Encountered a Keyboard Quit Command\n", logtime);
break;
case SIGPIPE:
fprintf(stderr, "%s FATAL: Spine Encountered a Broken Pipe\n", logtime);
break;
default:
fprintf(stderr, "%s FATAL: Spine Encountered An Unhandled Exception Signal Number: '%d'\n", logtime, spine_signal);
break;
}
}
static int spine_fatal_signals[] = {
SIGINT,
SIGPIPE,
SIGSEGV,
SIGBUS,
SIGFPE,
SIGQUIT,
SIGSYS,
SIGABRT,
0
};
static struct sigaction previous_sigchld;
static int previous_sigchld_saved = FALSE;
/*! \fn void install_spine_signal_handler(void)
* \brief installs the spine signal handler to stop certain calls from
* abending Spine.
*
*/
void install_spine_signal_handler(void) {
/* Set a handler for any fatal signal not already handled */
int i;
struct sigaction sa;
void (*ohandler)(int);
/* Child lifecycle code retains PIDs until waitpid() reaps them. Normalize
* an inherited SIG_IGN disposition so children remain zombies and their
* PIDs cannot be recycled before Spine observes their exit. */
if (sigaction(SIGCHLD, NULL, &previous_sigchld) == 0) {
previous_sigchld_saved = TRUE;
}
sa.sa_handler = SIG_DFL;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGCHLD, &sa, NULL);
for (i=0; spine_fatal_signals[i]; ++i) {
sigaction(spine_fatal_signals[i], NULL, &sa);
if (sa.sa_handler == SIG_DFL) {
sa.sa_handler = spine_signal_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sigaction(spine_fatal_signals[i], &sa, NULL);
}
}
for (i=0; spine_fatal_signals[i]; ++i) {
ohandler = signal(spine_fatal_signals[i], spine_signal_handler);
if (ohandler != SIG_DFL) {
signal(spine_fatal_signals[i], ohandler);
}
}
return;
}
/*! \fn void uninstall_spine_signal_handler(void)
* \brief uninstalls the spine signal handler.
*
*/
void uninstall_spine_signal_handler(void) {
/* Remove a handler for any fatal signal handled */
int i;
struct sigaction sa;
void (*ohandler)(int);
if (previous_sigchld_saved) {
sigaction(SIGCHLD, &previous_sigchld, NULL);
previous_sigchld_saved = FALSE;
}
for (i=0; spine_fatal_signals[i]; ++i) {
sigaction(spine_fatal_signals[i], NULL, &sa);
if (sa.sa_handler == spine_signal_handler) {
sa.sa_handler = SIG_DFL;
sigaction(spine_fatal_signals[i], &sa, NULL);
}
}
for ( i=0; spine_fatal_signals[i]; ++i ) {
ohandler = signal(spine_fatal_signals[i], SIG_DFL);
if (ohandler != spine_signal_handler) {
signal(spine_fatal_signals[i], ohandler);
}
}
}