From c98012f23667ae9a7951bc272a992befea05fa2e Mon Sep 17 00:00:00 2001 From: Vasili Pascal Date: Mon, 16 Nov 2026 15:36:40 +0200 Subject: [PATCH 1/4] style(website): no long dashes in the monitoring-stack article House style: em dashes out of marketing copy, replaced by commas, colons and sentence breaks. Titles use a pipe separator. --- website/app/monitoring-stack-security-events/page.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/website/app/monitoring-stack-security-events/page.tsx b/website/app/monitoring-stack-security-events/page.tsx index 1587aba..b75d80c 100644 --- a/website/app/monitoring-stack-security-events/page.tsx +++ b/website/app/monitoring-stack-security-events/page.tsx @@ -23,13 +23,13 @@ export const metadata: Metadata = { canonical: PAGE_PATH }, openGraph: { - title: 'Three Security Events in One Month Reshaped Our Monitoring Stack — StackdogApp', + title: 'Three Security Events in One Month Reshaped Our Monitoring Stack | StackdogApp', description: 'Where Stackdog stands after PHP2Shell and SSHole, and why it now installs with one command.', url: getSiteUrl() + PAGE_PATH }, twitter: { - title: 'Three Security Events in One Month Reshaped Our Monitoring Stack — StackdogApp', + title: 'Three Security Events in One Month Reshaped Our Monitoring Stack | StackdogApp', description: 'Where Stackdog stands after PHP2Shell and SSHole, and why it now installs with one command.' } @@ -39,7 +39,7 @@ const layers = [ { icon: ShieldAlert, title: 'PHP2Shell (v0.2.8–0.2.9)', - body: 'Forced the version-check layer: which PHP builds predate the fix, on the host and inside every running container — and a detector for the exploit\u2019s actual footprint, the request that runs PHP out of memory while it is still being parsed.' + body: 'Forced the version-check layer: which PHP builds predate the fix, on the host and inside every running container, and a detector for the exploit\u2019s actual footprint: the request that runs PHP out of memory while it is still being parsed.' }, { icon: TerminalSquare, @@ -252,11 +252,11 @@ export default function MonitoringStackSecurityEventsPage() { It doesn't patch anything (upgrading is the fix), a ban arrives after the fact and mostly stops scanners and repeat attempts, bans are IPv4-only right now, and version-based CVE findings mean "a fix is missing", not "you are - exploitable" — distributions backport fixes. Every alert says to check your + exploitable": distributions backport fixes. Every alert says to check your vendor's advisory.

- Happy to answer questions about the detection side — and if you've been hit by + Happy to answer questions about the detection side. And if you've been hit by something the logs didn't catch, we genuinely want to hear about it.{' '} Contact us From eb64bb84a8056db9564147644cf864dbd3364e4b Mon Sep 17 00:00:00 2001 From: Vasili Pascal Date: Thu, 19 Nov 2026 10:41:11 +0100 Subject: [PATCH 2/4] feat(detectors): NGINX2Root exposure, crash, RCE, SCTP and HTTP/2 spray detection Detect the five NGINX2Root nginx bugs (CVE-2026-123007 and four more) plus the kernel step of the chain, on the host and in running containers: - vuln.nginx2root: flag nginx builds older than 1.30.7/1.31.9 whose config reaches a specific CVE (HTTP/2, HTTP/3, mail proxy, proxy_pass + SSI/mirror), naming the CVE and its mitigation. Reads NGINX_VERSION from official images and the package databases, following nginx's two version tracks. - nginx.worker-crash: alert on a run of nginx workers dying on memory faults. - web.worker-exec: alert when a web-server worker executes a program (RCE). - kernel.sctp-socket / kernel.sctp-exposed: alert on SCTP socket creation and a loaded SCTP module -- the unpatched root-escalation step. - nginx.http2-spray: workload heuristic for the heap-spray footprint (inbound bytes up while logged requests stay flat), from Docker stats + log counts. The eBPF collector now traces socket() so SCTP creation is captured alongside execve/connect/openat/ptrace. None of these name a client address, so none ban. --- ebpf/src/maps.rs | 19 + ebpf/src/syscalls.rs | 21 +- src/collectors/ebpf/types.rs | 66 ++ src/detectors/mod.rs | 66 ++ src/detectors/nginx.rs | 1220 ++++++++++++++++++++++++++++++++ src/detectors/php_shell/mod.rs | 3 + src/docker/client.rs | 8 +- src/events/syscall.rs | 17 + src/sniff/config.rs | 20 + src/sniff/mod.rs | 106 +++ 10 files changed, 1544 insertions(+), 2 deletions(-) create mode 100644 src/detectors/nginx.rs diff --git a/ebpf/src/maps.rs b/ebpf/src/maps.rs index 1ff8d6b..dc3844f 100644 --- a/ebpf/src/maps.rs +++ b/ebpf/src/maps.rs @@ -11,6 +11,7 @@ pub union EbpfEventData { pub connect: ConnectData, pub openat: OpenatData, pub ptrace: PtraceData, + pub socket: SocketData, pub raw: [u8; 264], } @@ -120,5 +121,23 @@ impl PtraceData { } } +#[repr(C)] +#[derive(Clone, Copy)] +pub struct SocketData { + pub domain: u32, + pub type_: u32, + pub protocol: u32, +} + +impl SocketData { + pub const fn empty() -> Self { + Self { + domain: 0, + type_: 0, + protocol: 0, + } + } +} + #[map(name = "EVENTS")] pub static EVENTS: RingBuf = RingBuf::with_byte_size(256 * 1024, 0); diff --git a/ebpf/src/syscalls.rs b/ebpf/src/syscalls.rs index cdfbd06..55d0f7f 100644 --- a/ebpf/src/syscalls.rs +++ b/ebpf/src/syscalls.rs @@ -13,7 +13,8 @@ use aya_ebpf::{ }; use crate::maps::{ - ConnectData, EbpfEventData, EbpfSyscallEvent, ExecveData, OpenatData, PtraceData, EVENTS, + ConnectData, EbpfEventData, EbpfSyscallEvent, ExecveData, OpenatData, PtraceData, SocketData, + EVENTS, }; const SYSCALL_ARG_START: usize = 16; @@ -23,6 +24,7 @@ const SYS_EXECVE: u32 = 59; const SYS_CONNECT: u32 = 42; const SYS_OPENAT: u32 = 257; const SYS_PTRACE: u32 = 101; +const SYS_SOCKET: u32 = 41; const AF_INET: u16 = 2; const AF_INET6: u16 = 10; @@ -52,6 +54,12 @@ pub fn trace_ptrace(ctx: TracePointContext) -> i32 { 0 } +#[tracepoint(name = "sys_enter_socket", category = "syscalls")] +pub fn trace_socket(ctx: TracePointContext) -> i32 { + let _ = unsafe { try_trace_socket(&ctx) }; + 0 +} + unsafe fn try_trace_execve(ctx: &TracePointContext) -> Result<(), i64> { let filename_ptr = read_u64_arg(ctx, 0)? as *const u8; let argv_ptr = read_u64_arg(ctx, 1)? as *const u64; @@ -123,6 +131,17 @@ unsafe fn try_trace_ptrace(ctx: &TracePointContext) -> Result<(), i64> { submit_event(&event) } +unsafe fn try_trace_socket(ctx: &TracePointContext) -> Result<(), i64> { + let mut event = base_event(ctx, SYS_SOCKET); + let data = SocketData { + domain: read_u64_arg(ctx, 0)? as u32, + type_: read_u64_arg(ctx, 1)? as u32, + protocol: read_u64_arg(ctx, 2)? as u32, + }; + event.data = EbpfEventData { socket: data }; + submit_event(&event) +} + fn base_event(ctx: &TracePointContext, syscall_id: u32) -> EbpfSyscallEvent { let mut event = EbpfSyscallEvent::empty(); event.pid = ctx.tgid(); diff --git a/src/collectors/ebpf/types.rs b/src/collectors/ebpf/types.rs index 9a034ff..2aee335 100644 --- a/src/collectors/ebpf/types.rs +++ b/src/collectors/ebpf/types.rs @@ -41,6 +41,8 @@ pub union EbpfEventData { pub openat: OpenatData, /// ptrace data pub ptrace: PtraceData, + /// socket data + pub socket: SocketData, /// Raw bytes pub raw: [u8; 128], } @@ -129,6 +131,28 @@ pub struct PtraceData { pub data: u64, } +/// socket-specific data +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct SocketData { + /// Address family (AF_INET, AF_INET6, ...) + pub domain: u32, + /// Socket type (SOCK_STREAM, SOCK_DGRAM, ...) + pub type_: u32, + /// Protocol (IPPROTO_TCP, IPPROTO_SCTP = 132, ...) + pub protocol: u32, +} + +impl SocketData { + pub const fn empty() -> Self { + Self { + domain: 0, + type_: 0, + protocol: 0, + } + } +} + impl EbpfSyscallEvent { /// Create a new event pub fn new(pid: u32, uid: u32, syscall_id: u32) -> Self { @@ -172,6 +196,7 @@ pub fn to_syscall_event(ebpf_event: &EbpfSyscallEvent) -> crate::events::syscall 42 => SyscallType::Connect, // sys_connect 257 => SyscallType::Openat, // sys_openat 101 => SyscallType::Ptrace, // sys_ptrace + 41 => SyscallType::Socket, // sys_socket _ => SyscallType::Unknown, }; @@ -200,6 +225,10 @@ pub fn to_syscall_event(ebpf_event: &EbpfSyscallEvent) -> crate::events::syscall // SAFETY: We interpret the union according to the syscall type. Some(ptrace_details(unsafe { &ebpf_event.data.ptrace })) } + SyscallType::Socket => { + // SAFETY: We interpret the union according to the syscall type. + Some(socket_details(unsafe { &ebpf_event.data.socket })) + } _ => None, }; @@ -250,6 +279,14 @@ fn ptrace_details(data: &PtraceData) -> crate::events::syscall::SyscallDetails { } } +fn socket_details(data: &SocketData) -> crate::events::syscall::SyscallDetails { + crate::events::syscall::SyscallDetails::Socket { + domain: data.domain, + type_: data.type_, + protocol: data.protocol, + } +} + fn decode_string(bytes: &[u8], declared_len: Option) -> Option { let first_nul = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len()); let len = declared_len @@ -373,6 +410,35 @@ mod tests { } } + #[test] + fn test_to_syscall_event_preserves_socket_details() { + let mut event = EbpfSyscallEvent::new(1234, 1000, 41); + event.set_comm(b"nginx"); + event.data = EbpfEventData { + socket: SocketData { + domain: 2, + type_: 1, + protocol: 132, + }, + }; + + let converted = event.to_syscall_event(); + assert_eq!(converted.comm.as_deref(), Some("nginx")); + assert_eq!(converted.socket_details(), Some((2, 1, 132))); + match converted.details { + Some(SyscallDetails::Socket { + domain, + type_, + protocol, + }) => { + assert_eq!(domain, 2); + assert_eq!(type_, 1); + assert_eq!(protocol, 132); + } + other => panic!("unexpected details: {:?}", other), + } + } + #[test] fn test_to_syscall_event_preserves_openat_details() { let mut event = EbpfSyscallEvent::new(1234, 1000, 257); diff --git a/src/detectors/mod.rs b/src/detectors/mod.rs index 4d96532..d98353e 100644 --- a/src/detectors/mod.rs +++ b/src/detectors/mod.rs @@ -9,6 +9,7 @@ pub mod cve_watch; pub(crate) mod http_request; mod integrity; mod ml; +pub mod nginx; pub mod php2shell; pub mod php_shell; pub mod sshole; @@ -25,12 +26,18 @@ use self::cve_watch::CveWatchMonitor; use self::http_request::{extract_request, HttpRequest}; use self::integrity::FileIntegrityMonitor; use self::ml::MlBehavioralDetector; +pub use self::nginx::TrafficWindow; +use self::nginx::{ + Http2SprayMonitor, KernelSctpMonitor, NginxExposureMonitor, NginxWorkerCrashDetector, + SctpSocketMonitor, WebWorkerExecMonitor, +}; use self::php2shell::{Php2ShellAttemptDetector, PhpVersionMonitor, PhpWorkerCrashDetector}; use self::php_shell::{ ContainerFilesystem, PhpShellAccessDetector, PhpShellOptions, PhpShellScanner, ScanRoot, }; use self::sshole::{SshPasswordLoginDetector, SshVersionMonitor}; use crate::database::connection::DbPool; +use crate::events::syscall::SyscallEvent; use crate::sniff::analyzer::{AnomalySeverity, LogAnomaly}; use crate::sniff::reader::LogEntry; @@ -108,6 +115,11 @@ pub struct DetectorRegistry { php_shell_scanner: PhpShellScanner, php_version_monitor: PhpVersionMonitor, sshole_monitor: SshVersionMonitor, + nginx_exposure_monitor: NginxExposureMonitor, + kernel_sctp_monitor: KernelSctpMonitor, + web_worker_exec_monitor: WebWorkerExecMonitor, + sctp_socket_monitor: SctpSocketMonitor, + http2_spray_monitor: Http2SprayMonitor, } impl DetectorRegistry { @@ -121,6 +133,11 @@ impl DetectorRegistry { php_shell_scanner: PhpShellScanner::new(), php_version_monitor: PhpVersionMonitor::new(), sshole_monitor: SshVersionMonitor::new(), + nginx_exposure_monitor: NginxExposureMonitor::new(), + kernel_sctp_monitor: KernelSctpMonitor, + web_worker_exec_monitor: WebWorkerExecMonitor, + sctp_socket_monitor: SctpSocketMonitor, + http2_spray_monitor: Http2SprayMonitor::new(), } } @@ -153,6 +170,7 @@ impl DetectorRegistry { )); self.register(PhpWorkerCrashDetector); self.register(Php2ShellAttemptDetector); + self.register(NginxWorkerCrashDetector); self.register(SshPasswordLoginDetector::new()); } @@ -226,6 +244,54 @@ impl DetectorRegistry { .collect() } + /// Flag nginx builds whose configuration reaches one of the NGINX2Root + /// CVEs, on the host and in running containers. + pub fn detect_nginx_exposure_anomalies( + &self, + containers: &[ContainerFilesystem], + host_root: Option<&str>, + ) -> Vec { + self.nginx_exposure_monitor + .detect(containers, host_root) + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect() + } + + /// Flag a loaded kernel SCTP module, the unpatched step of the NGINX2Root + /// root-escalation chain. + pub fn detect_kernel_sctp_anomalies(&self, host_root: Option<&str>) -> Vec { + self.kernel_sctp_monitor + .detect(host_root) + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect() + } + + /// Flag programs executed by web-server workers (the remote-code-execution + /// indicator) and SCTP sockets opened by workers or containers (the kernel + /// escalation step). Consumes syscall events from the eBPF collector, which + /// the `serve` runtime does not yet start. + pub fn detect_syscall_anomalies(&self, events: &[SyscallEvent]) -> Vec { + self.web_worker_exec_monitor + .detect(events) + .into_iter() + .chain(self.sctp_socket_monitor.detect(events)) + .map(|finding| finding.to_log_anomaly()) + .collect() + } + + /// Flag workloads whose inbound bytes grew while their logged request count + /// stayed small — the footprint of an HTTP/2 heap spray (CVE-2026-123007), + /// whose control frames are never logged. + pub fn detect_traffic_anomalies(&self, observations: &[TrafficWindow]) -> Vec { + self.http2_spray_monitor + .detect(observations) + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect() + } + /// Match the package inventory against public CVE feeds. The monitor does /// blocking file and network work, so it runs on a blocking thread rather /// than stalling the sniff runtime. diff --git a/src/detectors/nginx.rs b/src/detectors/nginx.rs new file mode 100644 index 0000000..b37ddd2 --- /dev/null +++ b/src/detectors/nginx.rs @@ -0,0 +1,1220 @@ +//! NGINX2Root exposure, nginx worker crashes, and the kernel SCTP step of the +//! chain. +//! +//! NGINX2Root is a set of five memory-corruption vulnerabilities in nginx +//! (CVE-2026-123007, CVE-2026-123633, CVE-2026-123634, CVE-2026-121810, +//! CVE-2026-113425) disclosed on 2026-11-18, plus a separate, unpatched Linux +//! kernel SCTP use-after-free that escalates the nginx worker to root, including +//! from inside a Docker container. The nginx bugs are only reachable when the +//! relevant feature is enabled, so this module answers three questions the +//! running system can answer without touching the network: +//! +//! - which nginx builds on the host and in running containers predate the fixed +//! releases, and which of the five CVEs their configuration actually exposes +//! (`vuln.nginx2root`); +//! - whether nginx workers keep dying on memory faults, which is what the +//! heap-corruption attempts leave behind (`nginx.worker-crash`); +//! - whether the kernel SCTP path the root-escalation uses is reachable +//! (`kernel.sctp-exposed`). +//! +//! None of these name a client address: the exploit's control frames are not +//! logged as requests, so none of them ever bans. +//! +//! Version rules follow the F5/nginx.org advisories of 2026-11-18 and Xint's +//! write-up; the fixed releases are nginx 1.30.7 (stable) and 1.31.9 (mainline). + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::SystemTime; + +use regex::Regex; + +use crate::detectors::audits::{parse_apk_installed, parse_dpkg_status}; +use crate::detectors::php2shell::VersionSource; +use crate::detectors::php_shell::{under_host_root, ContainerFilesystem}; +use crate::detectors::{DetectorFamily, DetectorFinding, LogDetector}; +use crate::events::syscall::{SyscallEvent, SyscallType}; +use crate::sniff::analyzer::AnomalySeverity; +use crate::sniff::reader::LogEntry; + +pub const EXPOSURE_DETECTOR_ID: &str = "vuln.nginx2root"; +pub const CRASH_DETECTOR_ID: &str = "nginx.worker-crash"; +pub const SCTP_DETECTOR_ID: &str = "kernel.sctp-exposed"; +pub const SCTP_SOCKET_DETECTOR_ID: &str = "kernel.sctp-socket"; +pub const SPRAY_DETECTOR_ID: &str = "nginx.http2-spray"; +pub const WORKER_EXEC_DETECTOR_ID: &str = "web.worker-exec"; + +/// IPPROTO_SCTP: the protocol number an SCTP socket is created with. +const IPPROTO_SCTP: u32 = 132; + +/// The five NGINX2Root CVEs, for the descriptions. +const CVES: &str = + "CVE-2026-123007, CVE-2026-123633, CVE-2026-123634, CVE-2026-121810, CVE-2026-113425"; + +/// First fixed release per upstream track: stable 1.30.7, mainline 1.31.9. +const FIXED_STABLE: (u32, u32, u32) = (1, 30, 7); +const FIXED_MAINLINE: (u32, u32, u32) = (1, 31, 9); + +/// Package databases, relative to a filesystem root. +const PACKAGE_DATABASES: &[&str] = &["var/lib/dpkg/status", "lib/apk/db/installed"]; + +/// Crashes in one batch of log lines before it is worth an alert. A single +/// worker segfault is usually a flaky module; a run of them is a memory +/// corruption attempt grooming the heap. +const CRASH_THRESHOLD: usize = 3; + +/// Findings per pass for the exposure check, so a fleet of nginx containers +/// cannot turn one advisory into a flood. +const MAX_EXPOSURE_FINDINGS: usize = 40; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Exposure { + /// A source or image build older than the fix for its track. + Vulnerable { + fixed_in: String, + }, + /// A distribution package older than the upstream fix. Distributions + /// backport fixes without changing the upstream number, so only the + /// vendor's advisory can say. + CheckVendor { + fixed_in: String, + }, + Patched, +} + +/// `1.31.8` out of `1.31.8`, `1:1.31.8-1~bookworm` or `1.26.3-r0`. nginx has no +/// epoch and no patch suffix beyond the distribution revision, so the leading +/// `major.minor.patch` is the upstream version. +fn upstream_version(version: &str) -> Option<(u32, u32, u32)> { + let without_epoch = version.split_once(':').map_or(version, |(_, rest)| rest); + let numeric: String = without_epoch + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '.') + .collect(); + let mut parts = numeric.split('.').filter(|part| !part.is_empty()); + let major = parts.next()?.parse().ok()?; + let minor = parts.next()?.parse().ok()?; + let patch = parts.next().and_then(|part| part.parse().ok()).unwrap_or(0); + Some((major, minor, patch)) +} + +/// The NGINX2Root exposure of `version`, or None if it is not a nginx version. +/// +/// nginx keeps two live tracks: odd minors are mainline (1.31.x, fixed at +/// 1.31.9) and even minors are stable (1.30.x, fixed at 1.30.7). A version is +/// fixed when it reaches the fix on its own track, so the comparison is +/// per-track rather than one linear threshold: 1.31.0 is mainline and still +/// vulnerable even though it sorts above 1.30.7. +pub fn exposure(version: &str, from_distro_package: bool) -> Option { + let (major, minor, patch) = upstream_version(version)?; + + if major > 1 { + return Some(Exposure::Patched); + } + if major < 1 { + return Some(triage( + "1.30.7 (stable) or 1.31.9 (mainline)".to_string(), + from_distro_package, + )); + } + + // major == 1. Odd minor = mainline, even minor = stable. + let fixed = if minor % 2 == 1 { + FIXED_MAINLINE + } else { + FIXED_STABLE + }; + if (minor, patch) >= (fixed.1, fixed.2) { + return Some(Exposure::Patched); + } + + // Name the fix for the version's own track when it is on one of the two + // fixed tracks; otherwise point at both. + let fixed_in = if minor == fixed.1 { + format!("{}.{}.{}", fixed.0, fixed.1, fixed.2) + } else { + "1.30.7 (stable) or 1.31.9 (mainline)".to_string() + }; + Some(triage(fixed_in, from_distro_package)) +} + +fn triage(fixed_in: String, from_distro_package: bool) -> Exposure { + if from_distro_package { + Exposure::CheckVendor { fixed_in } + } else { + Exposure::Vulnerable { fixed_in } + } +} + +/// Package databases carry the server binary: `nginx` (Debian, Ubuntu, Alpine, +/// nginx.org) and the split Debian builds. `nginx-common`, `nginx-doc` and the +/// module packages either carry no binary or follow the same version, so they +/// are left out to keep one finding per install. +fn is_nginx_server_package(name: &str) -> bool { + matches!( + name, + "nginx" | "nginx-core" | "nginx-full" | "nginx-light" | "nginx-extras" + ) +} + +/// What an nginx build's configuration reaches. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct NginxFeatures { + /// `http2 on` or `listen ... http2` (CVE-2026-123007, CVE-2026-123633). + pub http2: bool, + /// Requests are proxied to a backend (CVE-2026-123633, CVE-2026-121810). + pub proxy_pass_backend: bool, + /// `http3 on` or `listen ... quic` (CVE-2026-121810). + pub http3: bool, + /// A `mail` block with `proxy on` (CVE-2026-113425). + pub mail_proxy: bool, + /// `proxy_pass` with a variable, plus an SSI or mirror subrequest + /// (CVE-2026-123634). + pub proxy_pass_variable_subrequest: bool, +} + +/// The features a configuration exposes, read from its text. nginx config is +/// free-form, so this is a whole-text scan: it answers "is this feature on +/// anywhere the server will load", not "which server block". That is the right +/// granularity for exposure, because a feature reachable in any loaded block is +/// reachable by an attacker. This runs a handful of times per pass, so the +/// patterns are compiled inline rather than cached. +pub fn config_features(content: &str) -> NginxFeatures { + let lower = content.to_ascii_lowercase(); + let listen = Regex::new(r"\blisten\b[^;]*").expect("valid regex"); + let proxy_pass = Regex::new(r"\bproxy_pass\b[^;]*").expect("valid regex"); + + let listen_with = |needle: &str| { + listen + .captures_iter(&lower) + .any(|directive| directive[0].contains(needle)) + }; + + let http2 = contains(&lower, r"\bhttp2\s+on\b") || listen_with("http2"); + let http3 = contains(&lower, r"\bhttp3\s+on\b") || listen_with("quic"); + + let proxy_pass_backend = proxy_pass.is_match(&lower); + let proxy_pass_variable = proxy_pass + .captures_iter(&lower) + .any(|directive| directive[0].contains('$')); + let subrequest = contains(&lower, r"\bssi\s+on\b") || contains(&lower, r"\bmirror\b"); + let proxy_pass_variable_subrequest = proxy_pass_variable && subrequest; + + let mail_proxy = (contains(&lower, r"\bmail\s*\{") && contains(&lower, r"\bproxy\s+on\b")) + || contains(&lower, r"\bauth_http\b"); + + NginxFeatures { + http2, + proxy_pass_backend, + http3, + mail_proxy, + proxy_pass_variable_subrequest, + } +} + +fn contains(haystack: &str, pattern: &str) -> bool { + Regex::new(pattern).expect("valid regex").is_match(haystack) +} + +/// Which of the five CVEs a configuration reaches, with the mitigation that +/// closes it until the build is upgraded. +fn applicable_cves(features: &NginxFeatures) -> Vec<(&'static str, &'static str, &'static str)> { + let mut out = Vec::new(); + if features.http2 { + out.push(( + "CVE-2026-123007", + "HTTP/2 is enabled", + "set http2 off, or remove http2 from the listen directives", + )); + } + if features.http2 && features.proxy_pass_backend { + out.push(( + "CVE-2026-123633", + "HTTP/2 is enabled and requests are proxied to a backend", + "set http2 off, or remove http2 from the listen directives", + )); + } + if features.http3 { + out.push(( + "CVE-2026-121810", + "HTTP/3 (QUIC) listeners are enabled", + "remove the quic/http3 listeners, or set http3 off", + )); + } + if features.mail_proxy { + out.push(( + "CVE-2026-113425", + "the mail proxy is enabled", + "bind mail listeners to loopback, or firewall them to trusted networks", + )); + } + if features.proxy_pass_variable_subrequest { + out.push(( + "CVE-2026-123634", + "proxy_pass builds the upstream from a variable and an SSI or mirror subrequest resolves the same name", + "point proxy_pass at a fixed upstream group", + )); + } + out +} + +/// A nginx installation found on the host or in a container. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NginxInstall { + /// `host` or the container name. + pub owner: String, + pub version: String, + pub source: VersionSource, +} + +/// A parsed package database and the file state it was parsed from. +struct CachedPackages { + modified: SystemTime, + size: u64, + packages: Vec<(String, String)>, +} + +#[derive(Default)] +pub struct NginxExposureMonitor { + /// Parsed package databases keyed by path, reused while the file's + /// modification time and size stay the same. + cache: Mutex>, +} + +impl NginxExposureMonitor { + pub fn new() -> Self { + Self::default() + } + + pub fn detect( + &self, + containers: &[ContainerFilesystem], + host_root: Option<&str>, + ) -> Vec { + let mut findings = self.scan_root("host", &under_host_root(host_root, "/")); + + for container in containers { + let mut installs = Vec::new(); + let mut features = NginxFeatures::default(); + if let Some(merged_dir) = &container.merged_dir { + let root = under_host_root(host_root, merged_dir); + installs.extend(self.installs_under(&container.name, &root)); + features = config_features(&nginx_config_text(&root)); + } + // Official nginx images set NGINX_VERSION even when the image was + // built from source and carries no package. + if let Some(version) = &container.nginx_version { + installs.push(NginxInstall { + owner: container.name.clone(), + version: version.clone(), + source: VersionSource::ImageEnv, + }); + } + if !installs.is_empty() { + findings.extend(findings_for(&container.name, &installs, &features)); + } + } + + findings.truncate(MAX_EXPOSURE_FINDINGS); + findings + } + + fn scan_root(&self, owner: &str, root: &Path) -> Vec { + let installs = self.installs_under(owner, root); + if installs.is_empty() { + return Vec::new(); + } + let features = config_features(&nginx_config_text(root)); + findings_for(owner, &installs, &features) + } + + fn installs_under(&self, owner: &str, root: &Path) -> Vec { + PACKAGE_DATABASES + .iter() + .flat_map(|database| self.packages(&root.join(database))) + .filter(|(name, _)| is_nginx_server_package(name)) + .map(|(name, version)| NginxInstall { + owner: owner.to_string(), + version, + source: VersionSource::Package { name }, + }) + .collect() + } + + fn packages(&self, path: &Path) -> Vec<(String, String)> { + let Ok(metadata) = std::fs::metadata(path) else { + return Vec::new(); + }; + let modified = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH); + let size = metadata.len(); + + if let Ok(cache) = self.cache.lock() { + if let Some(cached) = cache.get(path) { + if cached.modified == modified && cached.size == size { + return cached.packages.clone(); + } + } + } + + let Ok(content) = std::fs::read_to_string(path) else { + return Vec::new(); + }; + let packages = if path.ends_with("installed") { + parse_apk_installed(&content) + } else { + parse_dpkg_status(&content) + }; + + if let Ok(mut cache) = self.cache.lock() { + cache.insert( + path.to_path_buf(), + CachedPackages { + modified, + size, + packages: packages.clone(), + }, + ); + } + packages + } +} + +/// The nginx configuration a root loads: `nginx.conf` plus everything under the +/// directories it commonly includes. Reads are best-effort: a missing directory +/// is simply empty. +fn nginx_config_text(root: &Path) -> String { + let dir = root.join("etc/nginx"); + let mut text = String::new(); + push_file(&mut text, &dir.join("nginx.conf")); + for sub in ["conf.d", "sites-enabled", "sites-available"] { + if let Ok(entries) = std::fs::read_dir(dir.join(sub)) { + for entry in entries.flatten() { + push_file(&mut text, &entry.path()); + } + } + } + text +} + +fn push_file(text: &mut String, path: &Path) { + if let Ok(content) = std::fs::read_to_string(path) { + text.push_str(&content); + text.push('\n'); + } +} + +/// One finding per exposed `(owner, CVE)`. The configuration decides which CVEs +/// are reachable; the build decides how sure we are. +pub fn findings_for( + owner: &str, + installs: &[NginxInstall], + features: &NginxFeatures, +) -> Vec { + let mut versions = Vec::new(); + let mut worst: Option = None; + let mut seen = HashSet::new(); + + for install in installs { + if !seen.insert((install.owner.as_str(), install.version.as_str())) { + continue; + } + let from_package = matches!(install.source, VersionSource::Package { .. }); + let Some(exposure) = exposure(&install.version, from_package) else { + continue; + }; + versions.push(install.version.clone()); + // Worst wins: Vulnerable > CheckVendor > Patched. + worst = Some(match (&worst, &exposure) { + (Some(Exposure::Vulnerable { fixed_in }), _) => Exposure::Vulnerable { + fixed_in: fixed_in.clone(), + }, + (_, Exposure::Vulnerable { fixed_in }) => Exposure::Vulnerable { + fixed_in: fixed_in.clone(), + }, + (Some(Exposure::CheckVendor { fixed_in }), _) => Exposure::CheckVendor { + fixed_in: fixed_in.clone(), + }, + (_, Exposure::CheckVendor { fixed_in }) => Exposure::CheckVendor { + fixed_in: fixed_in.clone(), + }, + (_, next) => next.clone(), + }); + } + + let version_label = if versions.is_empty() { + "an nginx build".to_string() + } else { + format!("nginx {}", versions.join(", ")) + }; + + let cves = applicable_cves(features); + + // A source or image build is the high-confidence case; a distribution + // package may carry a backported fix, so it is only a lead. With no version + // we can still report a feature we can see is on. A patched build reports + // nothing at all. + let (severity, confidence, fixed_in, framing) = match &worst { + Some(Exposure::Patched) => return Vec::new(), + Some(Exposure::Vulnerable { fixed_in }) => ( + AnomalySeverity::Critical, + 95, + fixed_in.clone(), + "vulnerable", + ), + Some(Exposure::CheckVendor { fixed_in }) => { + (AnomalySeverity::Medium, 60, fixed_in.clone(), "lead") + } + None => { + if cves.is_empty() { + return Vec::new(); + } + ( + AnomalySeverity::Medium, + 55, + "1.30.7 (stable) or 1.31.9 (mainline)".to_string(), + "unknown", + ) + } + }; + + // A build below the fix with no readable config still matters: we cannot + // say which of the five applies, so say that instead of staying quiet. + if cves.is_empty() { + return vec![DetectorFinding { + detector_id: EXPOSURE_DETECTOR_ID.into(), + family: DetectorFamily::Vulnerability, + description: format!( + "NGINX2Root: {} on {} predates the nginx fixes ({}). No configuration was readable to say which of the five apply, so assume the enabled features are exposed: upgrade to {} and restart nginx", + version_label, owner, CVES, fixed_in + ), + severity, + confidence, + sample_line: format!("{} {} unverified-config", owner, version_label), + }]; + } + + cves.into_iter() + .map(|(cve, feature, mitigation)| { + let description = match framing { + "vulnerable" => format!( + "NGINX2Root {} on {}: {} ({}). {} Upgrade to {} and restart nginx", + cve, owner, version_label, feature, mitigation, fixed_in + ), + "lead" => format!( + "NGINX2Root {} on {}: {} ({}). Distribution packages may carry a backported fix: check your vendor's advisory. {}, or upgrade to {} and restart nginx", + cve, owner, version_label, feature, mitigation, fixed_in + ), + _ => format!( + "NGINX2Root {} on {}: {} ({}), and no package version was found to confirm the fix. {} Verify the build is {} or later", + cve, owner, version_label, feature, mitigation, fixed_in + ), + }; + DetectorFinding { + detector_id: EXPOSURE_DETECTOR_ID.into(), + family: DetectorFamily::Vulnerability, + description, + severity: severity.clone(), + confidence, + sample_line: format!("{} {} {}", owner, version_label, cve), + } + }) + .collect() +} + +/// nginx workers dying on memory faults, from the nginx error log. +pub struct NginxWorkerCrashDetector; + +impl LogDetector for NginxWorkerCrashDetector { + fn id(&self) -> &'static str { + CRASH_DETECTOR_ID + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Execution + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let crashes: Vec<&LogEntry> = entries + .iter() + .filter(|entry| is_nginx_worker_crash(&entry.line)) + .collect(); + + if crashes.len() < CRASH_THRESHOLD { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: CRASH_DETECTOR_ID.into(), + family: DetectorFamily::Execution, + description: format!( + "nginx workers crashed {} times on memory faults. Repeated worker crashes are what attempts against the NGINX2Root memory-corruption bugs ({}) leave behind; check the nginx version and the connections at those times", + crashes.len(), + CVES + ), + severity: if crashes.len() >= 10 { + AnomalySeverity::High + } else { + AnomalySeverity::Medium + }, + confidence: 70, + sample_line: crashes[0].line.clone(), + }] + } +} + +/// nginx: `2026/11/18 12:00:00 [alert] 31#0: worker process 32 exited on signal +/// 11 (SIGSEGV)` (src/os/unix/ngx_process_cycle.c). nginx names the signal and +/// may append `- core dumped`. +fn is_nginx_worker_crash(line: &str) -> bool { + let lower = line.to_ascii_lowercase(); + lower.contains("worker process") + && lower.contains("exited on signal") + && [ + "(sigsegv", + "(sigbus", + "(sigabrt", + "(sigill", + "signal 11", + "signal 7", + "signal 6", + "signal 4", + ] + .iter() + .any(|signal| lower.contains(signal)) +} + +/// Whether a web-server worker process executed a program (`web.worker-exec`). +/// +/// A web worker (nginx, Apache, php-fpm) serves requests; it does not exec a +/// program as part of normal operation. When one does, the process has almost +/// certainly been hijacked — the classic end state of a remote-code-execution +/// exploit such as NGINX2Root (CVE-2026-123007). This is the "programs started +/// by an nginx worker" indicator, matched on the process that calls exec, which +/// the eBPF collector captures at syscall entry before exec replaces it. +/// +/// It reads syscall events, which come from the eBPF collector. That source is +/// not yet started by the `serve` runtime (see `detect_syscall_anomalies`), so +/// this is ready to consume events the moment the collector is wired in. +pub struct WebWorkerExecMonitor; + +/// Comms of processes that serve web traffic and should never exec a program. +const WEB_WORKERS: &[&str] = &[ + "nginx", + "httpd", + "apache2", + "php-fpm", + "lighttpd", + "caddy", + "openresty", +]; + +impl WebWorkerExecMonitor { + pub fn detect(&self, events: &[SyscallEvent]) -> Vec { + events + .iter() + .filter(|event| { + matches!( + event.syscall_type, + SyscallType::Execve | SyscallType::Execveat + ) + }) + .filter(|event| { + event + .comm + .as_deref() + .is_some_and(|comm| WEB_WORKERS.contains(&comm)) + }) + .map(|event| { + let comm = event.comm.as_deref().unwrap_or("web worker"); + let program = event + .exec_details() + .and_then(|(filename, _args, _argc)| filename.clone()) + .unwrap_or_else(|| "an unknown program".to_string()); + DetectorFinding { + detector_id: WORKER_EXEC_DETECTOR_ID.into(), + family: DetectorFamily::Execution, + description: format!( + "A web server worker ({}) executed {}. Web workers do not run programs, so this is a strong sign the process was hijacked by remote code execution (e.g. NGINX2Root, {}); identify the command and the connection, and isolate the host or container", + comm, program, CVES + ), + severity: AnomalySeverity::Critical, + confidence: 90, + sample_line: format!("pid {} {} exec {}", event.pid, comm, program), + } + }) + .collect() + } +} + +/// Whether a web-worker or container process created an SCTP socket +/// (`kernel.sctp-socket`). +/// +/// The unpatched Linux kernel SCTP use-after-free is what the NGINX2Root chain +/// uses to turn the nginx worker into root, including out of a Docker +/// container. Creating an SCTP socket is the first step of that escalation. +/// SCTP from an ordinary host process is legitimate (telecom, VoIP), so this +/// only fires where SCTP is surprising: a web-server worker, or anything inside +/// a container. Like `web.worker-exec`, it reads eBPF syscall events. +pub struct SctpSocketMonitor; + +impl SctpSocketMonitor { + pub fn detect(&self, events: &[SyscallEvent]) -> Vec { + events + .iter() + .filter_map(|event| { + if event.syscall_type != SyscallType::Socket { + return None; + } + let (_domain, _type_, protocol) = event.socket_details()?; + if protocol != IPPROTO_SCTP { + return None; + } + let comm = event.comm.as_deref().unwrap_or("unknown"); + let is_worker = WEB_WORKERS.contains(&comm); + let in_container = event.container_id.is_some(); + if !is_worker && !in_container { + return None; + } + let (severity, who) = if is_worker { + (AnomalySeverity::Critical, "a web server worker") + } else { + (AnomalySeverity::High, "a container process") + }; + Some(DetectorFinding { + detector_id: SCTP_SOCKET_DETECTOR_ID.into(), + family: DetectorFamily::Execution, + description: format!( + "{} ({}) created an SCTP socket. SCTP is the path the NGINX2Root chain uses to escalate the nginx worker to root through an unpatched Linux kernel use-after-free ({}); isolate the host or container, and block the sctp module if it is not needed", + who, comm, CVES + ), + severity, + confidence: 85, + sample_line: format!("pid {} {} socket sctp", event.pid, comm), + }) + }) + .collect() + } +} + +/// The HTTP/2 heap-spray footprint (`nginx.http2-spray`). +/// +/// The CVE-2026-123007 exploit drives the heap over HTTP/2 with control frames +/// that are never logged as requests. At the workload level that shows up as a +/// lot of inbound data moving while the access log stays quiet: received bytes +/// grow, the request count does not. This is a heuristic read of that mismatch, +/// not a per-connection measurement (Docker reports per-container totals, not +/// per connection), so it is a review signal rather than a certainty: a large +/// single upload can look similar. Correlate with `nginx.worker-crash` and +/// `web.worker-exec` to tell an attack from a big download. +#[derive(Debug, Clone)] +pub struct Http2SprayMonitor { + /// Inbound bytes in one window before the mismatch is worth reporting. + min_inbound_bytes: u64, + /// Inbound bytes per logged request above which the traffic and the log + /// disagree. A web server rarely serves a request that carries this much + /// inbound data and logs nothing about it. + max_bytes_per_request: u64, +} + +impl Default for Http2SprayMonitor { + fn default() -> Self { + Self { + min_inbound_bytes: 16 * 1024 * 1024, + max_bytes_per_request: 512 * 1024, + } + } +} + +impl Http2SprayMonitor { + pub fn new() -> Self { + Self::default() + } + + pub fn detect(&self, observations: &[TrafficWindow]) -> Vec { + observations + .iter() + .filter_map(|traffic| { + if traffic.inbound_bytes < self.min_inbound_bytes { + return None; + } + // Inbound with nothing logged is the invisible-frame signature. + // Otherwise a huge amount of data per logged request says the + // bytes and the log disagree. + let bytes_per_request = traffic + .inbound_bytes + .checked_div(traffic.request_count) + .unwrap_or(u64::MAX); + if bytes_per_request <= self.max_bytes_per_request { + return None; + } + let (severity, why) = if traffic.request_count == 0 { + ( + AnomalySeverity::High, + "received data but logged no requests".to_string(), + ) + } else { + ( + AnomalySeverity::Medium, + format!( + "carried {} inbound bytes per logged request", + bytes_per_request + ), + ) + }; + Some(DetectorFinding { + detector_id: SPRAY_DETECTOR_ID.into(), + family: DetectorFamily::Web, + description: format!( + "{} moved {} inbound bytes in a window while logging only {} request(s): it {}. The CVE-2026-123007 HTTP/2 heap spray looks like this because its control frames are never logged; check for nginx worker crashes and outbound connections, and treat a one-off large upload as benign", + traffic.owner, traffic.inbound_bytes, traffic.request_count, why + ), + severity, + confidence: 55, + sample_line: format!( + "{} inbound_bytes={} requests={}", + traffic.owner, traffic.inbound_bytes, traffic.request_count + ), + }) + }) + .collect() + } +} + +/// One workload's traffic over a window: bytes received and requests logged. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct TrafficWindow { + pub owner: String, + pub inbound_bytes: u64, + pub request_count: u64, +} + +/// Whether the kernel SCTP path the NGINX2Root root-escalation uses is +/// reachable: the `sctp` module is loaded on the host. +/// +/// The kernel bug is unpatched, so the only mitigation is to stop the module +/// loading (`install sctp /bin/false`). A loaded module is the concrete, +/// actionable state: the use-after-free path is live here. A module that is +/// merely loadable is not reported, because that is the default everywhere and +/// would only add noise. The kernel is shared, so this is host-level only. +pub struct KernelSctpMonitor; + +impl KernelSctpMonitor { + pub fn detect(&self, host_root: Option<&str>) -> Vec { + let root = under_host_root(host_root, "/"); + if !module_loaded(&root) { + return Vec::new(); + } + + let blocked = sctp_blocked(&root); + let (severity, confidence, advice) = if blocked { + ( + AnomalySeverity::Low, + 60, + "a modprobe.d rule blocks sctp, but the module is already loaded; a rule only stops it loading, so `rmmod sctp` (or reboot) to drop it", + ) + } else { + ( + AnomalySeverity::High, + 85, + "on hosts that do not need SCTP, block it until the kernel fix lands: `echo 'install sctp /bin/false' > /etc/modprobe.d/zz-block-sctp.conf`", + ) + }; + + vec![DetectorFinding { + detector_id: SCTP_DETECTOR_ID.into(), + family: DetectorFamily::Configuration, + description: format!( + "The Linux kernel SCTP module is loaded and reachable. The NGINX2Root chain uses an unpatched SCTP use-after-free to escalate the nginx worker to root, including out of a Docker container. {}", + advice + ), + severity, + confidence, + sample_line: format!("{} proc/modules sctp", root.display()), + }] + } +} + +fn module_loaded(root: &Path) -> bool { + std::fs::read_to_string(root.join("proc/modules")) + .map(|content| { + content + .lines() + .any(|line| line.split_whitespace().next() == Some("sctp")) + }) + .unwrap_or(false) +} + +fn sctp_blocked(root: &Path) -> bool { + let dir = root.join("etc/modprobe.d"); + let Ok(entries) = std::fs::read_dir(&dir) else { + return false; + }; + entries.flatten().any(|entry| { + let path = entry.path(); + if path.extension().and_then(|ext| ext.to_str()) != Some("conf") { + return false; + } + std::fs::read_to_string(&path) + .map(|content| { + content.lines().any(|line| { + let lower = line.to_ascii_lowercase(); + lower.contains("sctp") + && (lower.contains("install sctp /bin/false") + || lower.contains("install sctp /bin/true") + || lower.contains("blacklist sctp")) + }) + }) + .unwrap_or(false) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::Utc; + + use crate::events::syscall::SyscallDetails; + + fn entries(lines: &[&str]) -> Vec { + lines + .iter() + .map(|line| LogEntry { + source_id: "nginx".into(), + timestamp: Utc::now(), + line: (*line).into(), + metadata: HashMap::new(), + }) + .collect() + } + + #[test] + fn test_upstream_builds_below_the_fix_are_vulnerable() { + assert_eq!( + exposure("1.31.8", false), + Some(Exposure::Vulnerable { + fixed_in: "1.31.9".to_string() + }) + ); + assert_eq!( + exposure("1.30.6", false), + Some(Exposure::Vulnerable { + fixed_in: "1.30.7".to_string() + }) + ); + assert_eq!( + exposure("1.9.5", false), + Some(Exposure::Vulnerable { + fixed_in: "1.30.7 (stable) or 1.31.9 (mainline)".to_string() + }) + ); + } + + #[test] + fn test_fixed_tracks_are_patched() { + assert_eq!(exposure("1.31.9", false), Some(Exposure::Patched)); + assert_eq!(exposure("1.30.7", false), Some(Exposure::Patched)); + // A mainline release after the fix sorts above 1.30.7 but is its own + // track: 1.31.0 is still vulnerable, 1.32.x and 1.31.10 are not. + assert_eq!( + exposure("1.31.0", false), + Some(Exposure::Vulnerable { + fixed_in: "1.31.9".to_string() + }) + ); + assert_eq!(exposure("1.32.0", false), Some(Exposure::Patched)); + assert_eq!(exposure("1.31.10", false), Some(Exposure::Patched)); + } + + #[test] + fn test_distribution_packages_only_lead() { + assert_eq!( + exposure("1:1.31.8-1~bookworm", true), + Some(Exposure::CheckVendor { + fixed_in: "1.31.9".to_string() + }) + ); + assert_eq!( + exposure("1.22.1-9+deb12u2", true), + Some(Exposure::CheckVendor { + fixed_in: "1.30.7 (stable) or 1.31.9 (mainline)".to_string() + }) + ); + } + + #[test] + fn test_non_versions_are_ignored() { + assert_eq!(exposure("latest", false), None); + assert_eq!(exposure("", false), None); + } + + #[test] + fn test_feature_detection_finds_each_cve() { + let http2 = config_features("server {\n listen 443 ssl http2;\n}\n"); + assert!(http2.http2); + assert!(!http2.http3); + + let http2_directive = config_features("server {\n listen 443 ssl;\n http2 on;\n}\n"); + assert!(http2_directive.http2); + + let http3 = config_features("server {\n listen 443 quic;\n http3 on;\n}\n"); + assert!(http3.http3); + + let mail = config_features("mail {\n proxy on;\n auth_http localhost:9000/auth;\n}\n"); + assert!(mail.mail_proxy); + + let resolver = + config_features("location / {\n proxy_pass http://$backend;\n mirror /m;\n}\n"); + assert!(resolver.proxy_pass_variable_subrequest); + + // A fixed upstream with no subrequest does not reach the resolver bug. + let fixed_upstream = + config_features("location / {\n proxy_pass http://backend;\n mirror /m;\n}\n"); + assert!(!fixed_upstream.proxy_pass_variable_subrequest); + + let plain = config_features("server {\n listen 80;\n root /var/www;\n}\n"); + assert_eq!(plain, NginxFeatures::default()); + } + + #[test] + fn test_applicable_cves_map_features_to_mitigations() { + let features = NginxFeatures { + http2: true, + proxy_pass_backend: true, + http3: true, + mail_proxy: true, + proxy_pass_variable_subrequest: true, + }; + let cves: Vec<&str> = applicable_cves(&features) + .into_iter() + .map(|c| c.0) + .collect(); + assert!(cves.contains(&"CVE-2026-123007")); + assert!(cves.contains(&"CVE-2026-123633")); + assert!(cves.contains(&"CVE-2026-121810")); + assert!(cves.contains(&"CVE-2026-113425")); + assert!(cves.contains(&"CVE-2026-123634")); + + // HTTP/2 without a backend proxy drops the HTTP/2+proxy CVE but keeps + // the flow-control one. + let http2_only = NginxFeatures { + http2: true, + ..NginxFeatures::default() + }; + let cves: Vec<&str> = applicable_cves(&http2_only) + .into_iter() + .map(|c| c.0) + .collect(); + assert!(cves.contains(&"CVE-2026-123007")); + assert!(!cves.contains(&"CVE-2026-123633")); + } + + #[test] + fn test_vulnerable_build_with_http2_names_the_cve() { + let installs = vec![NginxInstall { + owner: "host".into(), + version: "1.31.8".into(), + source: VersionSource::ImageEnv, + }]; + let features = NginxFeatures { + http2: true, + proxy_pass_backend: true, + ..NginxFeatures::default() + }; + let findings = findings_for("host", &installs, &features); + let text: Vec<&str> = findings.iter().map(|f| f.description.as_str()).collect(); + assert!(text.iter().any(|d| d.contains("CVE-2026-123007"))); + assert!(text.iter().any(|d| d.contains("CVE-2026-123633"))); + assert!(findings + .iter() + .all(|f| f.severity == AnomalySeverity::Critical)); + } + + #[test] + fn test_patched_build_reports_nothing() { + let installs = vec![NginxInstall { + owner: "host".into(), + version: "1.31.9".into(), + source: VersionSource::ImageEnv, + }]; + let features = NginxFeatures { + http2: true, + ..NginxFeatures::default() + }; + assert!(findings_for("host", &installs, &features).is_empty()); + } + + #[test] + fn test_vulnerable_build_without_readable_config_still_warns() { + let installs = vec![NginxInstall { + owner: "host".into(), + version: "1.31.8".into(), + source: VersionSource::ImageEnv, + }]; + let findings = findings_for("host", &installs, &NginxFeatures::default()); + assert_eq!(findings.len(), 1); + assert!(findings[0] + .description + .contains("No configuration was readable")); + assert!(findings[0].description.contains("1.31.9")); + } + + #[test] + fn test_worker_crash_detects_nginx_signal_faults() { + assert!(is_nginx_worker_crash( + "2026/11/18 12:00:00 [alert] 31#0: worker process 32 exited on signal 11 (SIGSEGV)" + )); + assert!(is_nginx_worker_crash( + "2026/11/18 12:00:00 [alert] 31#0: worker process 32 exited on signal 11 (SIGSEGV - core dumped)" + )); + // A graceful shutdown is not a crash. + assert!(!is_nginx_worker_crash( + "2026/11/18 12:00:00 [alert] 31#0: worker process 32 exited on signal 3 (SIGQUIT)" + )); + assert!(!is_nginx_worker_crash( + "2026/11/18 12:00:00 [notice] start worker process 33" + )); + } + + #[test] + fn test_crash_detector_needs_a_run_of_faults() { + let detector = NginxWorkerCrashDetector; + let crash = "2026/11/18 [alert] 1#0: worker process 2 exited on signal 11 (SIGSEGV)"; + assert!(detector.detect(&entries(&[crash, crash])).is_empty()); + assert_eq!(detector.detect(&entries(&[crash, crash, crash])).len(), 1); + } + + #[test] + fn test_sctp_monitor_reports_only_when_loaded() { + let dir = std::env::temp_dir().join(format!("stackdog-sctp-{}", std::process::id())); + std::fs::create_dir_all(dir.join("proc")).unwrap(); + std::fs::create_dir_all(dir.join("etc/modprobe.d")).unwrap(); + + // Not loaded: nothing. + std::fs::write(dir.join("proc/modules"), "overlay 1 0 - Live 0x0\n").unwrap(); + let root = dir.to_string_lossy().into_owned(); + assert!(KernelSctpMonitor.detect(Some(&root)).is_empty()); + + // Loaded and unblocked: high severity. + std::fs::write( + dir.join("proc/modules"), + "sctp 123 1 - Live 0x0\noverlay 1 0 - Live 0x0\n", + ) + .unwrap(); + let findings = KernelSctpMonitor.detect(Some(&root)); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].severity, AnomalySeverity::High); + + // Loaded but blocked: low severity, still worth knowing. + std::fs::write( + dir.join("etc/modprobe.d/zz-block-sctp.conf"), + "install sctp /bin/false\n", + ) + .unwrap(); + let findings = KernelSctpMonitor.detect(Some(&root)); + assert_eq!(findings[0].severity, AnomalySeverity::Low); + + std::fs::remove_dir_all(&dir).unwrap(); + } + + fn exec_event(comm: &str, filename: &str) -> SyscallEvent { + SyscallEvent::builder() + .pid(1000) + .uid(101) + .syscall_type(SyscallType::Execve) + .comm(Some(comm.to_string())) + .details(Some(SyscallDetails::Exec { + filename: Some(filename.to_string()), + args: vec![filename.to_string()], + argc: 1, + })) + .build() + } + + #[test] + fn test_web_worker_exec_flags_compromised_worker() { + let monitor = WebWorkerExecMonitor; + let events = vec![ + exec_event("nginx", "/bin/sh"), + exec_event("bash", "/bin/ls"), + ]; + let findings = monitor.detect(&events); + assert_eq!(findings.len(), 1); + assert!(findings[0].description.contains("nginx")); + assert!(findings[0].description.contains("/bin/sh")); + assert_eq!(findings[0].severity, AnomalySeverity::Critical); + } + + #[test] + fn test_web_worker_exec_ignores_non_exec_and_non_workers() { + let monitor = WebWorkerExecMonitor; + let connect = SyscallEvent::builder() + .syscall_type(SyscallType::Connect) + .comm(Some("nginx".into())) + .build(); + let events = vec![connect, exec_event("postgres", "/bin/true")]; + assert!(monitor.detect(&events).is_empty()); + } + + fn socket_event(comm: &str, protocol: u32, container: Option<&str>) -> SyscallEvent { + SyscallEvent::builder() + .syscall_type(SyscallType::Socket) + .comm(Some(comm.to_string())) + .container_id(container.map(|c| c.to_string())) + .details(Some(SyscallDetails::Socket { + domain: 2, + type_: 1, + protocol, + })) + .build() + } + + #[test] + fn test_sctp_socket_flags_worker_and_container() { + let monitor = SctpSocketMonitor; + let events = vec![ + socket_event("nginx", 132, None), + socket_event("app", 132, Some("c1")), + socket_event("app", 132, None), + socket_event("nginx", 6, None), + ]; + let findings = monitor.detect(&events); + assert_eq!(findings.len(), 2); + assert!(findings.iter().any(|f| { + f.severity == AnomalySeverity::Critical && f.description.contains("web server worker") + })); + assert!(findings.iter().any(|f| { + f.severity == AnomalySeverity::High && f.description.contains("container process") + })); + } + + fn window(owner: &str, inbound_bytes: u64, request_count: u64) -> TrafficWindow { + TrafficWindow { + owner: owner.to_string(), + inbound_bytes, + request_count, + } + } + + #[test] + fn test_http2_spray_flags_invisible_and_mismatched_traffic() { + let monitor = Http2SprayMonitor::default(); + let observations = vec![ + window("nginx", 64 * 1024 * 1024, 0), + window("nginx", 64 * 1024 * 1024, 4), + window("nginx", 1024, 0), + window("nginx", 64 * 1024 * 1024, 512), + ]; + let findings = monitor.detect(&observations); + assert_eq!(findings.len(), 2); + assert!(findings.iter().any(|f| f.severity == AnomalySeverity::High)); + assert!(findings + .iter() + .any(|f| f.severity == AnomalySeverity::Medium)); + // The high-severity one is the zero-request case. + assert!(findings + .iter() + .any(|f| f.severity == AnomalySeverity::High + && f.description.contains("logged no requests"))); + } +} diff --git a/src/detectors/php_shell/mod.rs b/src/detectors/php_shell/mod.rs index e1d160a..49ea0b2 100644 --- a/src/detectors/php_shell/mod.rs +++ b/src/detectors/php_shell/mod.rs @@ -112,6 +112,9 @@ pub struct ContainerFilesystem { pub merged_dir: Option, /// `PHP_VERSION` from the container environment, set by official PHP images. pub php_version: Option, + /// `NGINX_VERSION` from the container environment, set by official nginx + /// images (which build from source and carry no package). + pub nginx_version: Option, } /// A file the scanner flagged, as the access detector needs to know it. diff --git a/src/docker/client.rs b/src/docker/client.rs index 46ba2dd..74b3fcb 100644 --- a/src/docker/client.rs +++ b/src/docker/client.rs @@ -170,10 +170,15 @@ impl DockerClient { .graph_driver .and_then(|driver| driver.data.get("MergedDir").cloned()); let config = inspect.config.unwrap_or_default(); - let php_version = config.env.unwrap_or_default().into_iter().find_map(|var| { + let env = config.env.unwrap_or_default(); + let php_version = env.iter().find_map(|var| { var.strip_prefix("PHP_VERSION=") .map(|version| version.trim().to_string()) }); + let nginx_version = env.iter().find_map(|var| { + var.strip_prefix("NGINX_VERSION=") + .map(|version| version.trim().to_string()) + }); result.push(crate::detectors::php_shell::ContainerFilesystem { name: inspect @@ -186,6 +191,7 @@ impl DockerClient { mounts, merged_dir, php_version, + nginx_version, }); } diff --git a/src/events/syscall.rs b/src/events/syscall.rs index 3eb9641..0b576e3 100644 --- a/src/events/syscall.rs +++ b/src/events/syscall.rs @@ -75,6 +75,11 @@ pub enum SyscallDetails { addr: u64, data: u64, }, + Socket { + domain: u32, + type_: u32, + protocol: u32, + }, } impl SyscallEvent { @@ -127,6 +132,18 @@ impl SyscallEvent { _ => None, } } + + /// Get socket parameters `(domain, type, protocol)` if this is a socket event. + pub fn socket_details(&self) -> Option<(u32, u32, u32)> { + match self.details.as_ref() { + Some(SyscallDetails::Socket { + domain, + type_, + protocol, + }) => Some((*domain, *type_, *protocol)), + _ => None, + } + } } /// Builder for SyscallEvent diff --git a/src/sniff/config.rs b/src/sniff/config.rs index c7ff461..e5c9cdf 100644 --- a/src/sniff/config.rs +++ b/src/sniff/config.rs @@ -102,6 +102,10 @@ pub struct SniffConfig { pub sshole_enabled: bool, /// Match the package inventory against public CVE feeds (OSV + KEV) pub cve_watch_enabled: bool, + /// Flag nginx builds and configs that reach a NGINX2Root CVE + pub nginx2root_enabled: bool, + /// Flag a loaded kernel SCTP module, the unpatched NGINX2Root escalation + pub kernel_sctp_enabled: bool, /// Host directories to scan for PHP shells pub phpshell_paths: Vec, /// Container name/image fragments that mark a PHP workload @@ -333,6 +337,22 @@ impl SniffConfig { _ => None, }) .unwrap_or(true), + nginx2root_enabled: env::var("STACKDOG_NGINX2ROOT_ENABLED") + .ok() + .and_then(|v| match v.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + }) + .unwrap_or(true), + kernel_sctp_enabled: env::var("STACKDOG_KERNEL_SCTP_ENABLED") + .ok() + .and_then(|v| match v.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + }) + .unwrap_or(true), phpshell_paths: env_list("STACKDOG_PHPSHELL_PATHS").unwrap_or_default(), phpshell_container_patterns: env_list("STACKDOG_PHPSHELL_CONTAINERS") .map(|patterns| { diff --git a/src/sniff/mod.rs b/src/sniff/mod.rs index 4b41a31..a52ecf6 100644 --- a/src/sniff/mod.rs +++ b/src/sniff/mod.rs @@ -16,6 +16,7 @@ use crate::database::repositories::log_sources as log_sources_repo; use crate::detectors::php_shell; use crate::detectors::sshole; use crate::detectors::DetectorRegistry; +use crate::detectors::TrafficWindow; use crate::docker::DockerClient; use crate::ip_ban::{gate, IpBanConfig, IpBanEngine, OffenseInput}; use crate::sniff::analyzer::{LogAnalyzer, PatternAnalyzer}; @@ -41,6 +42,9 @@ pub struct SniffOrchestrator { tool_registry: ToolRegistry, /// Last AI analysis time per source (prevents re-analyzing every 30s) last_ai_analysis: Mutex>>, + /// Per-container inbound bytes at the last pass, for the HTTP/2 spray + /// heuristic's byte deltas. + traffic_prev_rx: Mutex>, } impl SniffOrchestrator { @@ -99,6 +103,7 @@ impl SniffOrchestrator { ip_ban, tool_registry, last_ai_analysis: Mutex::new(HashMap::new()), + traffic_prev_rx: Mutex::new(HashMap::new()), }) } @@ -198,6 +203,7 @@ impl SniffOrchestrator { || self.config.php_version_check_enabled || self.config.sshole_enabled || self.config.cve_watch_enabled + || self.config.nginx2root_enabled { match docker.list_container_filesystems().await { Ok(filesystems) => container_filesystems = filesystems, @@ -295,6 +301,35 @@ impl SniffOrchestrator { .await?; } + if self.config.nginx2root_enabled { + let anomalies = self.detectors.detect_nginx_exposure_anomalies( + &container_filesystems, + self.config.host_root.as_deref(), + ); + self.report_detector_batch( + &mut result, + "nginx2root", + container_filesystems.len() + 1, + "NGINX2Root exposure check", + anomalies, + ) + .await?; + } + + if self.config.kernel_sctp_enabled { + let anomalies = self + .detectors + .detect_kernel_sctp_anomalies(self.config.host_root.as_deref()); + self.report_detector_batch( + &mut result, + "kernel-sctp", + 1, + "Kernel SCTP check", + anomalies, + ) + .await?; + } + // 1. Discover sources log::debug!("Step 1: discovering log sources..."); let sources = discovery::discover_all(&self.config.extra_sources).await?; @@ -322,6 +357,7 @@ impl SniffOrchestrator { // 3. Process each source let reader_count = readers.len(); + let mut request_counts: HashMap = HashMap::new(); for (i, reader) in readers.iter_mut().enumerate() { log::debug!( "Step 3: reading source {}/{} ({})", @@ -338,6 +374,16 @@ impl SniffOrchestrator { result.total_entries += entries.len(); log::debug!(" Read {} entries", entries.len()); + // Requests logged per container this pass, for the HTTP/2 spray + // heuristic. Keyed by container id (source.path_or_id), which is + // stable across passes unlike source.id. + if let Some(source) = sources.get(i) { + if matches!(&source.source_type, LogSourceType::DockerContainer) { + *request_counts.entry(source.path_or_id.clone()).or_insert(0) += + entries.len() as u64; + } + } + // 4. Analyze log::debug!("Step 4: analyzing {} entries...", entries.len()); @@ -495,9 +541,69 @@ impl SniffOrchestrator { } } + // HTTP/2 spray heuristic: workloads whose inbound bytes grew this pass + // while their logged request count stayed small. Runs after the logs + // are read so the request counts are in. + if self.config.nginx2root_enabled { + let windows = self.gather_traffic_windows(&request_counts).await; + self.report_detector_batch( + &mut result, + "http2-spray", + windows.len(), + "HTTP/2 spray heuristic", + self.detectors.detect_traffic_anomalies(&windows), + ) + .await?; + } + Ok(result) } + /// Poll running containers for the inbound bytes they received since the + /// last pass, and pair each with the requests logged for it this pass. + /// Docker reports per-container totals, so this is a workload-level read of + /// the spray footprint, not a per-connection one. + async fn gather_traffic_windows( + &self, + request_counts: &HashMap, + ) -> Vec { + let Ok(docker) = DockerClient::new().await else { + return Vec::new(); + }; + let Ok(containers) = docker.list_containers(false).await else { + return Vec::new(); + }; + + // Gather the samples first: these awaits must not run while the delta + // state is locked. + let mut samples: Vec<(String, String, u64)> = Vec::new(); + for container in containers { + if container.status != "Running" { + continue; + } + if let Ok(stats) = docker.get_container_stats(&container.id).await { + samples.push((container.id, container.name, stats.network_rx)); + } + } + + let mut windows = Vec::new(); + let mut previous = self.traffic_prev_rx.lock().unwrap(); + for (id, name, current) in samples { + if let Some(prev) = previous.insert(id.clone(), current) { + let inbound_bytes = current.saturating_sub(prev); + if inbound_bytes == 0 { + continue; + } + windows.push(TrafficWindow { + owner: name, + inbound_bytes, + request_count: request_counts.get(&id).copied().unwrap_or(0), + }); + } + } + windows + } + async fn apply_ip_ban( &self, entries: &[reader::LogEntry], From 94ecc0a36362d0931a4cdf5c9f8888b7e514aa54 Mon Sep 17 00:00:00 2001 From: Vasili Pascal Date: Thu, 19 Nov 2026 10:41:19 +0100 Subject: [PATCH 3/4] docs: NGINX2Root coverage in README/CHANGELOG and a user announcement Document the NGINX2Root detectors (exposure, crash, RCE, SCTP, HTTP/2 spray) and their honest limits, add the STACKDOG_NGINX2ROOT_ENABLED and STACKDOG_KERNEL_SCTP_ENABLED toggles to .env.sample, and add a ready-to-send announcement telling users to update the trydirect/nginx image (restart, not reload) and install Stackdog for PHP2Shell and wider CVE coverage. --- .env.sample | 8 ++ CHANGELOG.md | 22 ++++ README.md | 34 +++++++ docs/nginx2root-user-announcement.md | 145 +++++++++++++++++++++++++++ 4 files changed, 209 insertions(+) create mode 100644 docs/nginx2root-user-announcement.md diff --git a/.env.sample b/.env.sample index 1766fe3..c349b05 100644 --- a/.env.sample +++ b/.env.sample @@ -127,6 +127,14 @@ RUST_BACKTRACE=full # public feeds (OSV + CISA's KEV catalog) and alert once per package and CVE. # Refreshed at least daily, which is what catches newly published CVEs. #STACKDOG_CVE_WATCH_ENABLED=true +# NGINX2Root (CVE-2026-123007 and four more, 2026-11-18): flag nginx builds +# older than the fixes whose config reaches one of the five CVEs (HTTP/2, +# HTTP/3, mail proxy, resolver), and flag a loaded kernel SCTP module -- the +# unpatched step of the root-escalation chain. Alert only; neither names a +# client address. `web.worker-exec` (a web worker that runs a program) is the +# RCE tell, and reads eBPF syscall events when that collector is enabled. +#STACKDOG_NGINX2ROOT_ENABLED=true +#STACKDOG_KERNEL_SCTP_ENABLED=true # --------------------------------------------------------------------------- # Dashboard container (docker-compose.yml / docker-compose.app.yml) diff --git a/CHANGELOG.md b/CHANGELOG.md index a814358..46063b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- NGINX2Root exposure (CVE-2026-123007, CVE-2026-123633, CVE-2026-123634, + CVE-2026-121810, CVE-2026-113425): `vuln.nginx2root` flags nginx builds older + than 1.30.7 (stable) / 1.31.9 (mainline) whose config reaches one of the five + CVEs — HTTP/2, HTTP/3, the mail proxy, or `proxy_pass` with a variable plus an + SSI/mirror subrequest. It reads `NGINX_VERSION` from official images and the + package databases, follows nginx's two version tracks, and names the CVE, the + feature and the mitigation. `nginx.worker-crash` alerts on a run of nginx + workers dying on memory faults. `kernel.sctp-exposed` alerts when the Linux + `sctp` module is loaded — the unpatched kernel step of the root-escalation + chain. `web.worker-exec` alerts when a web-server worker executes a program, + the RCE end state (reads eBPF syscall events, which `serve` does not yet + collect). `kernel.sctp-socket` alerts when a web worker or container process + creates an SCTP socket — the first step of the kernel root-escalation. + `nginx.http2-spray` is a workload-level heuristic that flags a container whose + inbound bytes grew while its logged request count stayed small, the footprint + of the HTTP/2 heap spray. The eBPF collector now traces `socket()` as well, so + SCTP socket creation is captured alongside execve/connect/openat/ptrace. None + of these name a client address, so none ban. + `STACKDOG_NGINX2ROOT_ENABLED` and `STACKDOG_KERNEL_SCTP_ENABLED` toggle them. + ## [0.3.1] - 2026-11-13 ### Added diff --git a/README.md b/README.md index 9d6eb16..31a2369 100644 --- a/README.md +++ b/README.md @@ -702,6 +702,40 @@ vendor's advisory". Very fresh CVEs may not be in the feeds yet; the specialized detectors above cover the ones we know in detail. `STACKDOG_CVE_WATCH_ENABLED=false` turns it off. +#### NGINX2Root exposure (CVE-2026-123007 and four more) + +NGINX2Root is a set of five memory-corruption bugs in nginx (disclosed +2026-11-18) plus an unpatched Linux kernel SCTP use-after-free that escalates +the nginx worker to root, including out of a Docker container. Each nginx bug is +reachable only when a feature is on, so exposure is configuration, not just +version. Fixed in nginx 1.30.7 (stable) and 1.31.9 (mainline). + +| Finding | When | Action | +|---|---|---| +| `vuln.nginx2root` | an nginx build older than the fixes whose config reaches one of the five CVEs: HTTP/2 (CVE-2026-123007, CVE-2026-123633), HTTP/3/QUIC (CVE-2026-121810), the mail proxy (CVE-2026-113425), or `proxy_pass` with a variable plus an SSI/mirror subrequest (CVE-2026-123634) | alert naming the CVE, the feature and the mitigation (e.g. `http2 off`) until you upgrade and **restart** nginx — a reload does not replace the binary. Never bans | +| `nginx.worker-crash` | a run of nginx workers dying on memory faults (SIGSEGV and friends) | alert: that crash spray is what heap-grooming exploits leave behind | +| `web.worker-exec` | a web-server worker (nginx, Apache, php-fpm) executed a program | Critical alert: workers do not exec, so the process was hijacked — the RCE end state | +| `nginx.http2-spray` | a workload moved a lot of inbound bytes while logging few or no requests | review alert: the HTTP/2 heap spray's control frames are never logged, so its traffic looks like this (heuristic — a large upload can too; correlate with the two above) | +| `kernel.sctp-socket` | a web worker or container process created an SCTP socket | Critical/High alert: the first step of the kernel root-escalation | +| `kernel.sctp-exposed` | the Linux `sctp` module is loaded | alert: the unpatched kernel step of the chain is reachable; block it (`install sctp /bin/false`) on hosts that do not need SCTP | + +Version exposure follows the two nginx tracks (odd minor = mainline, even = +stable), so 1.31.0 is still exposed though it sorts above 1.30.7. Source and +image builds are reported as exposed; distribution packages are only a lead, +because distros backport fixes without bumping the upstream number. Official +nginx images set `NGINX_VERSION`, which is read directly. +`STACKDOG_NGINX2ROOT_ENABLED=false` and `STACKDOG_KERNEL_SCTP_ENABLED=false` +turn the two checks off. + +Honest limits: the exploit's HTTP/2 control frames are not logged as requests, +so Stackdog cannot see the attack traffic itself — it sees the exposure (version +and config), the crash spray, the network footprint, and the RCE aftermath. +`web.worker-exec` and `kernel.sctp-socket` read eBPF syscall events, which the +`serve` runtime does not collect yet. `nginx.http2-spray` is a workload-level +heuristic from Docker byte counters and log counts, not a per-connection +measurement. `vuln.nginx2root`, `nginx.worker-crash` and `kernel.sctp-exposed` +run from logs and the filesystem with no extra source. + --- ## 📦 Installation diff --git a/docs/nginx2root-user-announcement.md b/docs/nginx2root-user-announcement.md new file mode 100644 index 0000000..c0a2731 --- /dev/null +++ b/docs/nginx2root-user-announcement.md @@ -0,0 +1,145 @@ +# Security update — NGINX2Root (CVE-2026-123007): update your trydirect/nginx image and install Stackdog + +**Severity:** Critical (CVSS 9.2) · **Disclosed:** 18 Nov 2026 · **Action required** + +> **TL;DR** — A critical, remotely exploitable nginx bug (CVE-2026-123007) is public. +> Update your `trydirect/nginx` image and **restart** your containers (a reload is +> not enough), then install Stackdog to keep watching for it and for other recent +> vulnerabilities such as PHP2Shell. + +--- + +## What happened + +On **18 November 2026**, five memory-corruption vulnerabilities in nginx — together +called **NGINX2Root** — were disclosed. The worst, **CVE-2026-123007**, is +**unauthenticated remote code execution over HTTP/2**: anyone who can reach a +server with HTTP/2 enabled can run commands as the nginx worker, with no +application bug required. A public proof-of-concept exists. A separate, still +**unpatched** Linux kernel bug can then escalate that access to **root**, +including escaping a Docker container onto the host. + +This affects any nginx reachable directly from the internet — including static +sites. The fixed releases are **nginx 1.30.7 (stable)** and **1.31.9 (mainline)** +(NGINX Plus 37.0.8.1 / 37.3.0.1). + +⚠️ **A configuration reload does _not_ fix this.** `nginx -s reload` keeps the old, +vulnerable binary answering. You must restart the process or re-create the +container. + +We've released an updated **`trydirect/nginx`** image that carries the fix. + +--- + +## 1 — Update your `trydirect/nginx` image + +Pull the fixed image and **re-create** your containers (do not keep running the +old one): + +```bash +# Pull the fixed image +docker pull trydirect/nginx:latest # or your pinned tag, e.g. trydirect/nginx: + +# docker compose +docker compose pull nginx +docker compose up -d --force-recreate nginx + +# docker run +docker stop && docker rm +docker run -d ... trydirect/nginx:latest +``` + +Confirm the running build is fixed: + +```bash +docker exec nginx -v +# expect 1.30.7 / 1.31.9 or later (distro builds may show an older upstream +# number while still carrying the backported fix — check your package version) +``` + +**If you can't update right now**, turn the affected features off as a stopgap and +restart: + +```nginx +http2 off; # CVE-2026-123007 / CVE-2026-123633 — or drop "http2" from listen +# remove quic/http3 listeners # CVE-2026-121810 +# point proxy_pass at a fixed upstream # CVE-2026-123634 (no variables + SSI/mirror) +# restrict mail listeners to trusted IPs # CVE-2026-113425 +``` + +On hosts that don't need SCTP, block the kernel escalation step too: + +```bash +echo 'install sctp /bin/false' | sudo tee /etc/modprobe.d/zz-block-sctp.conf +sudo rmmod sctp 2>/dev/null || true +``` + +--- + +## 2 — Install Stackdog for ongoing protection + +Stackdog is a lightweight security agent for Linux hosts and Docker containers — +real-time threat detection and response (a modern fail2ban, plus container and +host monitoring). One command to install: + +```bash +curl -fsSL https://raw.githubusercontent.com/trydirect/stackdog/main/install.sh | sudo bash +``` + +Stackdog watches for **NGINX2Root** and other recent vulnerabilities: + +| Threat | What Stackdog does | +|---|---| +| **NGINX2Root** (CVE-2026-123007 + 4 more) | Flags exposed nginx builds and the exact config that reaches each CVE (HTTP/2, HTTP/3, mail proxy, resolver) on the host and in containers; alerts on the worker-crash spray and on **any command run by an nginx worker** (the RCE tell); warns when the kernel SCTP escalation step is reachable. | +| **PHP2Shell** (CVE-2026-109618 / 109619) | Detects exposed PHP builds, PHP worker crashes, and the exploit footprint — and bans the clients driving it. | +| **SSHole** (CVE-2026-123158) | Flags vulnerable OpenSSH builds and bans password logins to key-only accounts. | +| **Everything else** (`vuln.cve-watch`) | Continuously matches every installed package on the host **and in containers** against OSV and CISA's known-exploited catalog. | + +It also does fail2ban-style IP bans, container quarantine, file-integrity +monitoring, and webshell detection. It **detects and responds** — it does not +patch, so keep your images updated. + +--- + +## How to tell if you were already hit + +The attack is deliberately quiet (its HTTP/2 control frames are never logged), so +look for the aftermath: + +- **Programs started by the nginx worker** — workers serve requests, they don't + run programs. Anything spawned by one is a strong sign of compromise: + ```bash + ps -u www-data -o pid,ppid,lstart,cmd # or your nginx user + ``` +- **Runs of nginx workers dying on memory faults** (signal 11 / SIGSEGV): + ```bash + sudo journalctl -u nginx --since "-24h" | grep -iE 'signal 11|segfault|worker process' + ``` +- **Loaded SCTP kernel module** (the root-escalation path): + ```bash + grep sctp /proc/modules + ``` + +If you see any of these, treat the host/container as compromised: isolate it, +rotate secrets, and investigate before bringing it back. + +--- + +## Summary + +1. **Update `trydirect/nginx`** and **restart / re-create** your containers — a + reload does not fix this. +2. **Install Stackdog** to continuously detect NGINX2Root, PHP2Shell, SSHole and + other vulnerabilities across your hosts and containers. +3. **Check the IOCs** above if you think you may have been exposed. + +Questions? See the full write-up on the Stackdog blog +(**CVE-2026-123007: NGINX2Root and how to protect your servers and containers**) +or reach out to the trydirect team. + +--- + +*Fill-in notes for the sender: confirm the exact `trydirect/nginx` tag to pull +(`:latest` vs a versioned tag) and the container/service names in the compose +examples to match how your users deploy it. The Stackdog install command and the +CVE facts are final.* From 86bcb8677f6f31944fb9c54ee384606b7b266ebe Mon Sep 17 00:00:00 2001 From: Vasili Pascal Date: Thu, 19 Nov 2026 10:41:28 +0100 Subject: [PATCH 4/4] feat(website): NGINX2Root blog post on stackdog.app Add a long-form article, "CVE-2026-123007: NGINX2Root and How to Protect Your Servers and Containers", covering the five CVEs and the kernel bug, the fixed releases, why a reload is not enough, the IOCs, the interim mitigations, and how Stackdog detects each step. Wired into the sitemap and the footer Explore list. --- website/app/nginx2root/page.tsx | 654 ++++++++++++++++++++++++++++++++ website/app/sitemap.ts | 6 + website/components/Footer.tsx | 5 + 3 files changed, 665 insertions(+) create mode 100644 website/app/nginx2root/page.tsx diff --git a/website/app/nginx2root/page.tsx b/website/app/nginx2root/page.tsx new file mode 100644 index 0000000..b1785e8 --- /dev/null +++ b/website/app/nginx2root/page.tsx @@ -0,0 +1,654 @@ +import type { Metadata } from 'next'; +import Link from 'next/link'; +import { ArrowRight, Boxes, FileSearch, ShieldAlert, TerminalSquare } from 'lucide-react'; +import CopyButton from '@/components/CopyButton'; +import { getSiteUrl } from '@/lib/config'; +import { buildDocsStructuredData, toJsonLd } from '@/lib/structured-data'; + +const PAGE_PATH = '/nginx2root'; + +const versionCommand = `# What is running, and on which track (odd minor = mainline, even = stable) +nginx -v 2>&1 + +# Distro packages backport fixes without bumping the upstream number: +# 1.26.3-1+deb12u3 can carry the fix while nginx -v still says 1.26.3. +dpkg -l nginx # Debian / Ubuntu +rpm -q nginx # RHEL / Alma / Rocky +apk info -e nginx # Alpine + +# Fixed: nginx 1.30.7 (stable) / 1.31.9 (mainline), NGINX Plus 37.0.8.1 / 37.3.0.1`; + +const restartCommand = `# A reload is not a restart. Reload keeps the old binary answering. +sudo systemctl restart nginx + +# Containers: pull the fixed image and re-create, don't reuse the old one +docker compose pull +docker compose up -d --force-recreate`; + +const mitigationCommand = `# CVE-2026-123007 / CVE-2026-123633: HTTP/2 off +http2 off; # or drop http2 from the listen directives + +# CVE-2026-121810: no QUIC listeners +# remove the quic/http3 listeners, or set http3 off + +# CVE-2026-123634: fixed upstream groups +proxy_pass http://backend_group; # not a variable, with SSI/mirror in play + +# CVE-2026-113425: mail proxy off or fenced +# bind mail listeners to loopback, or firewall them to trusted networks + +# Kernel step: block SCTP until the fix lands +echo 'install sctp /bin/false' > /etc/modprobe.d/zz-block-sctp.conf +rmmod sctp 2>/dev/null || true # a rule only stops it loading`; + +const iocCommand = `# Runs of nginx workers dying on memory faults +sudo journalctl -u nginx --since "-24h" | grep -i 'signal 11\\|segfault\\|worker process' + +# Programs running as the nginx worker user (workers never exec anything) +ps -u www-data -o pid,ppid,lstart,cmd + +# The kernel escalation path +grep sctp /proc/modules`; + +const installCommand = + 'curl -fsSL https://raw.githubusercontent.com/trydirect/stackdog/main/install.sh | sudo bash'; + +const cveCards = [ + { + id: 'CVE-2026-123633', + name: 'HTTP/2 use-after-free while proxying', + body: 'A use-after-free on the HTTP/2 proxy path, reached while nginx forwards requests to a backend when worker_connections is low. Turn HTTP/2 off on the frontend and the path closes.', + mitigation: 'http2 off' + }, + { + id: 'CVE-2026-121810', + name: 'HTTP/3 (QUIC) use-after-free while proxying', + body: 'The same shape of bug on the HTTP/3 path: a use-after-free while proxying over QUIC. Separate code, separate fix, same class of end state.', + mitigation: 'remove the quic/http3 listeners, or set http3 off' + }, + { + id: 'CVE-2026-123634', + name: 'Resolver use-after-free', + body: 'Triggered when proxy_pass builds its upstream from a variable and an SSI or mirror subrequest resolves the same name. The resolver frees a name the request still holds.', + mitigation: 'point proxy_pass at a fixed upstream group' + }, + { + id: 'CVE-2026-113425', + name: 'Mail proxy use-after-free', + body: 'A use-after-free in the mail proxy, reached through auth_http. The smallest audience of the five, and the smallest excuse for leaving it on.', + mitigation: 'bind mail listeners to loopback, or firewall them to trusted networks' + } +]; + +const iocs = [ + { + icon: TerminalSquare, + title: 'Programs spawned by the nginx worker', + body: 'nginx workers serve requests; they never execute anything. A process whose parent is a worker is the end state of a successful exploit, and the clearest signal you have.' + }, + { + icon: ShieldAlert, + title: 'Runs of worker crashes', + body: 'One segfault is a flaky module. Workers dying repeatedly on signal 11 (SIGSEGV) and other memory faults is what heap-grooming attempts against these bugs leave behind.' + }, + { + icon: Boxes, + title: 'HTTP/2 connections that grow while the log stays flat', + body: 'The exploit runs in control frames that are never logged as requests. Long-lived HTTP/2 connections whose received bytes keep climbing while the access log records nothing are the network signature.' + }, + { + icon: FileSearch, + title: 'SCTP socket activity', + body: 'SCTP sockets opened by nginx or from inside a container, followed by that container reaching the host kernel, is the escalation step of the chain in motion.' + } +]; + +const stackdogDetections = [ + [ + 'vuln.nginx2root', + 'Exposure detection. Flags nginx builds older than the fixes whose configuration actually reaches one of the five CVEs: it reads HTTP/2, HTTP/3, mail proxy and proxy_pass + SSI/mirror reachability from the config on the host and inside running containers, and reads NGINX_VERSION from official images and package databases. It follows nginx\u2019s two version tracks, names the CVE, and prints the exact mitigation \u2014 set http2 off, drop the quic listeners, and so on \u2014 next to the upgrade it does not replace.' + ], + [ + 'nginx.worker-crash', + 'Crash detection. Alerts on a run of nginx workers dying on memory faults (SIGSEGV and friends), which is what heap-grooming attempts against the memory-corruption bugs leave behind.' + ], + [ + 'nginx.http2-spray', + 'Network footprint. A workload-level heuristic that flags a container whose inbound bytes grew while its logged request count stayed small \u2014 what an HTTP/2 heap spray looks like, because its control frames are never logged. A review signal, not a certainty: a large upload can look similar, so it is read alongside the crash and RCE detections.' + ], + [ + 'web.worker-exec', + 'RCE detection. Alerts when a web-server worker \u2014 nginx, Apache or php-fpm \u2014 executes a program, watched through eBPF syscall monitoring. Web workers do not run programs, so this is the RCE end state.' + ], + [ + 'kernel.sctp-socket', + 'Kernel escalation in motion. Alerts when a web-server worker or a container process opens an SCTP socket, the first step of the unpatched kernel root-escalation, watched through eBPF syscall monitoring.' + ], + [ + 'kernel.sctp-exposed', + 'Kernel escalation exposure. Alerts when the Linux SCTP kernel module is loaded and reachable \u2014 the unpatched root-escalation step of the chain \u2014 and recommends blocking it with install sctp /bin/false when you do not need it.' + ], + [ + 'container.posture-risk', + 'Container posture. Flags privileged, host-network and host-PID containers \u2014 nginx inside one of those turns this chain straight into host root \u2014 and Stackdog can quarantine a compromised container while you investigate.' + ] +] as const; + +const faqStyleNotes = [ + { + title: 'It detects, it does not patch', + body: 'Upgrading nginx is the fix. Everything Stackdog does here is visibility: which builds are exposed, which features make them exposed, and whether anyone has used the exposure yet.' + }, + { + title: 'Version findings mean "a fix is missing"', + body: 'Not "you are exploitable". Distributions backport fixes without changing the upstream version number, so every version finding says to check your vendor\u2019s advisory before you panic.' + }, + { + title: 'No client address, no ban', + body: 'The exploit\u2019s control frames are not logged as requests, so none of these detectors ever bans an address. Bans stay where logs carry the client: webshells, PHP2Shell attempts, SSH and login brute force. Bans are IPv4-only today.' + } +]; + +export const metadata: Metadata = { + title: 'CVE-2026-123007: NGINX2Root and How to Protect Your Servers and Containers', + description: + 'NGINX2Root is five nginx memory-corruption bugs (CVE-2026-123007 and four more) plus an unpatched kernel SCTP escalation to root. The fixed releases, why a reload is not enough, the IOCs, and how Stackdog detects every step.', + keywords: [ + 'NGINX2Root', + 'CVE-2026-123007', + 'nginx vulnerability', + 'HTTP/2 RCE', + 'nginx container escape', + 'Stackdog Security' + ], + alternates: { + canonical: PAGE_PATH + }, + openGraph: { + title: 'CVE-2026-123007: NGINX2Root and How to Protect Your Servers and Containers | StackdogApp', + description: + 'Five nginx bugs, one unpatched kernel escalation, and a reload that fixes nothing. What to change today and where Stackdog sees each step.', + url: getSiteUrl() + PAGE_PATH + }, + twitter: { + title: 'CVE-2026-123007: NGINX2Root and How to Protect Your Servers and Containers | StackdogApp', + description: + 'Five nginx bugs, one unpatched kernel escalation, and a reload that fixes nothing. What to change today and where Stackdog sees each step.' + } +}; + +function CodeSample({ code, label }: { code: string; label: string }) { + return ( +

+
+

{label}

+ +
+
+        {code}
+      
+
+ ); +} + +function Step({ + number, + title, + children, + code, + label +}: { + number: number; + title: string; + children: React.ReactNode; + code: string; + label: string; +}) { + return ( +
  • +
    + Step {number} +

    {title}

    +
    {children}
    +
    +
    + +
    +
  • + ); +} + +export default function Nginx2RootPage() { + return ( +
    +