Repository navigation
fix(arbitrary-command): heap-allocate split-token buffer to avoid VLA stack overflow - #405
Merged
fcostaoliveira merged 1 commit intoMay 30, 2026
Conversation
… stack overflow arbitrary_command::split_command_to_args() declared `char buffer[command_len]` on the stack, sized by the input command's length. With --monitor-input replays this function is called per-request from the worker thread via shard_connection::fill_pipeline -> client::create_arbitrary_request, so any captured MONITOR line larger than the worker's stack (default 8-12 MB on Linux) blew the stack the moment the picker selected it: SIGSEGV, or "*** stack smashing detected ***" when glibc's canary caught it first. The crash handler then often re-crashed in _dl_fixup because the stack was already corrupted, which is why bug reports were typically truncated. Reproduced on current master (15dae38) and on the 2.3.1 release with a real 77 MB MONITOR capture containing one ~20 MB HSET (gzipped blob): memtier_benchmark -s host -p port -t 4 --clients 50 --pipeline 1 \ --monitor-input=replay.txt --command="__monitor_line@__" --requests=1000 Crashes at ~77% of the run. Raising `ulimit -s` past the longest line makes the workload complete cleanly, confirming the diagnosis. Fix: replace the VLA with a std::vector<char>, so the scratch buffer lives on the heap and is sized at any length the input demands. The function is called once per request, so a single heap allocation per call is acceptable in exchange for removing the stack-size dependency. Regression test (tests/test_monitor_input.py) generates a single "SET" "regression_key" "<16 MiB blob>" monitor line, runs memtier with --monitor-input + --command="__monitor_line@__", and asserts the run completes without crashing and that STRLEN on the server matches the sent value's length. Verified locally that the test FAILS on the pre-fix binary and PASSES with the fix. Fixes redis#404 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This was referenced May 30, 2026
paulorsousa
approved these changes
May 30, 2026
fcostaoliveira
added a commit
that referenced
this pull request
Jun 1, 2026
… RESP parsers (#421) Wires three coverage-guided libFuzzer harnesses for memtier_benchmark's in-process parsers so we catch the next adversarial-input bug (like the 19.97 MB MONITOR-input VLA stack overflow fixed in #405) without waiting for it to land in a real workload. Targets (tests/fuzz/): - split_command_to_args_fuzz: drives bytes into arbitrary_command::command and calls split_command_to_args(). Catches stack/heap overflows on the scratch buffer (the #405 bug), \xNN decode bugs, and unterminated-quote loops. - monitor_input_fuzz: writes input to a tmpfile each iteration and calls monitor_command_list::load_from_file(). Catches preamble-parsing edge cases, missing quotes, multi-MB lines. - redis_protocol_fuzz: feeds bytes through an evbuffer into protocol_factory(PROTOCOL_RESP2/RESP3)->parse_response(), looping until drained or a 64-iteration cap. Routes through the factory because the concrete redis_protocol class lives in protocol.cpp's TU. Build wiring: - New `--enable-fuzz` configure flag (configure.ac); requires clang++, errors out otherwise. Exposes a `FUZZ_ENABLED` automake conditional. - Makefile.am gains a `FUZZ_ENABLED` block that builds three noinst_PROGRAMS with -fsanitize=fuzzer,address,undefined -fno-omit-frame-pointer -g -O1. Re-compiles config_types.cpp / protocol.cpp / command_meta.cpp into the fuzz objects so the sanitizer flags don't leak into the main binary's build. - Default `./configure && make` is unaffected: the conditional only fires under --enable-fuzz. Tiny shim (tests/fuzz/fuzz_stubs.cpp): - Stubs benchmark_log() / benchmark_log_file_line() / is_redis_protocol() so we don't drag in memtier_benchmark.cpp (main, libevent loop, stats stack, ...). Also provides dead-stub overrides for object_generator vtable slots referenced via monitor_command_list::get_random_command — the fuzzers never call them. Seed corpora (tests/fuzz/corpus/{split,monitor,resp}/): - split: basic SET, quoted/single-quoted values, \xNN decodes, malformed hex, embedded NUL, unterminated quotes, a 1.5 KB long-quoted string (libFuzzer grows it from there), escape mixes, whitespace-heavy. - monitor: redis MONITOR lines, the `[ proxy ... ]` preamble shape, unterminated quotes, lone quote, embedded NUL, comment-then-cmd. - resp: RESP2 simple/error/integer/bulk/null/array, *1\r\n nested chain, $INT_MAX bulk-length header, negative length, truncated bulk; RESP3 map / push (`>`) / attribute (`|`) / double / big-number / pipelined. First byte selects RESP2 vs RESP3. CI (.github/workflows/fuzz-smoke.yml): - Matrix over the three targets. Installs clang, autoreconf, configures with --enable-fuzz, builds the target, runs it for `-max_total_time=60 -rss_limit_mb=2048 -timeout=25 -max_len=33554432` on the seed corpus. `max_len=32 MiB` keeps the original 19.97 MB MONITOR line reachable per the issue's acceptance criterion. - Uploads crash-*/leak-*/timeout-*/oom-* artifacts on failure. Validation: - All three fuzzers build cleanly: `CC=clang CXX=clang++ ./configure --enable-fuzz && make split_command_to_args_fuzz monitor_input_fuzz redis_protocol_fuzz`. - Default `./configure && make` still produces a working memtier_benchmark. - Each fuzzer runs 30 s on the seed corpus with exit 0 when the config_types.cpp VLA is heap-promoted (i.e. with #405 applied). - Load-bearing acceptance: with the VLA still in place (config_types.cpp:520 `char buffer[command_len];`), running the split_command_to_args_fuzz against a 20 MB long-quoted-string seed reproduces the stack overflow within milliseconds: AddressSanitizer: stack-overflow ... in arbitrary_command::split_command_to_args() Re-applying the std::vector<char> fix from #405 makes the same 20 MB input run cleanly. This is precisely the regression we wanted the fuzzer to catch. - Fuzzers also surface latent UBSan-recoverable diagnostics on master (split: VLA-of-zero on empty input; resp: signed integer overflow in protocol.cpp:642 m_bulk_len + 2 when bulk-length is near LONG_MAX). These are reported but don't fail CI under default UBSan recover mode; follow-up PRs can address them. Fixes #407 Co-authored-by: Claude Sonnet 4.6 <[email protected]>
fcostaoliveira
added a commit
that referenced
this pull request
Jun 1, 2026
…rror=vla (#415) * fix(arbitrary-command): heap-allocate split-token buffer to avoid VLA stack overflow arbitrary_command::split_command_to_args() declared `char buffer[command_len]` on the stack, sized by the input command's length. With --monitor-input replays this function is called per-request from the worker thread via shard_connection::fill_pipeline -> client::create_arbitrary_request, so any captured MONITOR line larger than the worker's stack (default 8-12 MB on Linux) blew the stack the moment the picker selected it: SIGSEGV, or "*** stack smashing detected ***" when glibc's canary caught it first. The crash handler then often re-crashed in _dl_fixup because the stack was already corrupted, which is why bug reports were typically truncated. Reproduced on current master (15dae38) and on the 2.3.1 release with a real 77 MB MONITOR capture containing one ~20 MB HSET (gzipped blob): memtier_benchmark -s host -p port -t 4 --clients 50 --pipeline 1 \ --monitor-input=replay.txt --command="__monitor_line@__" --requests=1000 Crashes at ~77% of the run. Raising `ulimit -s` past the longest line makes the workload complete cleanly, confirming the diagnosis. Fix: replace the VLA with a std::vector<char>, so the scratch buffer lives on the heap and is sized at any length the input demands. The function is called once per request, so a single heap allocation per call is acceptable in exchange for removing the stack-size dependency. Regression test (tests/test_monitor_input.py) generates a single "SET" "regression_key" "<16 MiB blob>" monitor line, runs memtier with --monitor-input + --command="__monitor_line@__", and asserts the run completes without crashing and that STRLEN on the server matches the sent value's length. Verified locally that the test FAILS on the pre-fix binary and PASSES with the fix. Fixes #404 Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(stack-safety): bound sscanf/strcat, iterative mbulk teardown, -Werror=vla Static-audit follow-up to PR #405 / issue #404 (VLA stack overflow in arbitrary_command::split_command_to_args). Addresses the rest of the latent stack-allocation foot-guns surfaced by the audit in issue #406. protocol.cpp:949 (HIGH): memcache_text_protocol::parse_response did sscanf(line, "%s %s %u %u %u", prefix /*[50]*/, key /*[256]*/, ...) against a server-derived `line` from evbuffer_readln. A malicious or buggy memcached server replying with "VALUE <very-long-key> 0 999\r\n" overwrote the worker thread's stack past key[256]. Width-specifier the sscanf to %49s / %255s. protocol.h:60-67 (MED): ~mbulk_size_el recursively delete'd children built from RESP. A nested array `*1\r\n*1\r\n*1\r\n…` blew the destructor's recursion stack on protocol_response::clear(). Converted to an iterative worklist that steals each visited node's children before deleting it, so the triggered destructor's loop finds an empty children-vector and never recurses. memtier_benchmark.cpp:234 (MED): benchmark_log_file_line() did snprintf("%s:%u: ") + unbounded strcat(fmt) into a 1024-byte stack buffer. Today every caller passes a literal `fmt`, but the unbounded strcat is one careless refactor away from being attacker-influenced. Replaced with a bounded snprintf-append. configure.ac (guardrail): Added -Werror=vla so the next attempt to size a stack allocation by attacker-controlled input fails at compile time, not at customer site. Pre-requisite: the VLA fix from PR #405 is cherry-picked here so this branch builds independently; once #405 lands the cherry-pick will no-op into master. LOW/hygiene findings from issue #406 (PATH_MAX stack buffers, run_stats fmtbufs, statsd request buffer, sun_path strncpy) are left for a follow-up PR — they're bounded today and migrating to std::string is churn-heavy. Refs #406 Co-Authored-By: Claude Sonnet 4.6 <[email protected]> --------- Co-authored-by: Claude Sonnet 4.6 <[email protected]>
fcostaoliveira
added a commit
that referenced
this pull request
Jun 1, 2026
…e backtrace Follow-up to issue #404 / PR #405 (and addresses #412). The bug report attached to #404 was truncated at "CLIENT LIST OUTPUT": the crash handler started, printed STACK TRACE / INFO OUTPUT, then re-faulted inside _dl_fixup when it tried to call an stdio function for the first time from the signal context. Three structural fixes: 1) sigaltstack(2) is now installed on the main thread (in setup_crash_handlers) and on every worker (at cg_thread_start entry). Without this, SA_ONSTACK was silently inert and a SIGSEGV caused by stack overflow re-faulted on the exhausted stack — producing no report at all. 64 KiB per thread, malloc'd best-effort (silently no-op on OOM). 2) Pre-warm symbols at startup. Before registering the handler, prewarm_crash_handler() calls backtrace(), backtrace_symbols_fd() (output discarded to /dev/null), fprintf(stderr, "") + fflush, and event_get_version(). Each touch forces the dynamic linker to resolve the PLT entry NOW, so when the handler later runs there is no _dl_fixup on the signal path. _dl_fixup is not async-signal-safe; this is the specific failure mode that truncated #404's report. 3) print_all_threads_stack_trace now uses backtrace_symbols_fd (the documented async-signal-safe variant) instead of the malloc-using backtrace_symbols. The crashing thread may hold the malloc arena lock, or the heap may be corrupt; both make backtrace_symbols re-fault. Plus an alarm(5) watchdog at the top of crash_handler: if the handler itself hangs (e.g. mid-print_client_list while iterating a torn vector), the process is killed after 5 s instead of leaving a half-written report. SIGALRM is explicitly reset to SIG_DFL so the watchdog terminates rather than recursing into the handler. Out of scope for this PR (left as TODO referencing #412): - Replacing fprintf with a hand-rolled write()+safe_itoa formatter (large refactor; pre-warm gets us most of the value without it). - Replacing localtime+strftime with a static-buffer formatter. - Caching getpid() in a static at startup. - Adding new test scenarios (stack overflow, double-free, etc.) — follow-up; existing tests still pass with these changes. Refs #412 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
fcostaoliveira
added a commit
that referenced
this pull request
Jun 1, 2026
Closes the Week-1 portion of issue #411 (sanitizer matrix coverage gaps that allowed the PR #405 VLA stack-overflow to ship). * Bump sanitizer job `timeout-minutes` from 15 to 45 so longer cells can complete without the artifical step cap. * Extend `tsan.yml` from 3 cells to the same 6-cell shape as ASAN/UBSan (adds TLSv1.2, TLSv1.3, cluster-TLS). * Add a `STRESS=1` matrix axis to all three sanitizer workflows (standalone + cluster) which routes `tests/run_tests.sh` to the new `tests/test_sanitizer_stress.py` exclusively. * New `tests/test_sanitizer_stress.py` with 5 deliberate sanitizer stress scenarios that the default matrix never exercised: - test_huge_data_size_under_load (2 MiB --data-size, t=8 c=16) - test_huge_monitor_line_cluster (hash-tagged keys, cluster-only) - test_huge_key_prefix_cluster_pipeline (16 KiB prefix, pipeline=50) - test_reconnect_churn_long_run (--reconnect-interval, standalone) - test_debug_flag_paths (--debug codepaths) Each test is small but stress-meaningful; the full file completes in ~25s locally (standalone + cluster), well below CI budget. Out of scope for this PR (tracked as Month-1 / Quarter-1 follow-ups in the issue): MSAN workflow, slow-network `tc netem` cells, 49/99-shard mega-cluster sanitizer cells, FD-exhaustion / mid-run-server-kill tests. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
fcostaoliveira
added a commit
that referenced
this pull request
Jun 1, 2026
… hardening Issue #408 follow-up to PR #405 / issue #404 (VLA stack-overflow in arbitrary_command::split_command_to_args). The existing tests/test_monitor_input.py covers five canonical lines and one 16 MiB ASCII regression; not enough to prevent the next parser-level CVE in load_from_file / split_command_to_args / extract_command_type. This commit adds a black-box fuzz harness: tests/fuzz/monitor_input_corpus/ -- 18 seed files exercising empty / header-only / minimal / mixed-case / redacted-AUTH / hex-escape / embedded-NUL / embedded-quote / single-quote / unterminated-quote / trailing-garbage / CRLF-mixed / UTF-8 BOM / no-trailing-newline / all-commands.json / partial-truncation / binary-gzip-blob / pathological-quote-storm tests/fuzz/fuzz_monitor_input.py -- ~250 LoC mutating fuzzer driver. Per iteration: pick a seed, apply a random chain of mutators (bitflip / chop / dup / inject_nul / grow up to 8 MiB / crlf-jitter / quote-storm), write to tmpfile, run memtier_benchmark --monitor-input=<f> --command="__monitor_line@__" --requests=10 against a local redis, and flag any SIGSEGV, glibc "stack smashing detected", AddressSanitizer report, or 30s timeout. Non-zero exit is fine -- the contract is "report and exit, never crash". Findings on current master (200 iterations across the 18 seeds, default ulimit -s 12500): * 7 crash-class findings (~3.5%) -- all SIGSEGV mid-fill_pipeline, consistent with the VLA path PR #405 fixes plus follow-ups in the sibling issues (#406 / #407 / #409 cluster_slots crash). Reproducer files are emitted alongside the fuzzer logs. CI wiring is intentionally NOT added to this PR. The fuzzer surfaces real bugs that need separate fixes; wiring nightly cron + on-PR smoke follows once #405 / #406 / #407 / #409 land. See PR description for the phased plan. Refs #408 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
fcostaoliveira
added a commit
that referenced
this pull request
Jun 1, 2026
Adds a defensive test fixture exercising client-side RESP-response parser branches that the audit in #409 flagged as unaudited (bulk-length overflow, RESP3 push/verbatim/map edge cases, malformed CLUSTER SLOTS, unsolicited replies, truncated frames). The fixture consists of: * `tests/fixtures/mock_redis_resp_fuzzer.py` -- a small (~200 LoC) mock-redis server that lets the HELLO/AUTH/SELECT handshake pass with benign replies and then serves a single adversarial RESP fixture to the first workload command and half-closes the connection. * `tests/fixtures/resp_payloads/*.bin` -- 12 in-tree deterministic byte sequences, one per targeted parser branch. The README maps each fixture to the specific protocol.cpp / cluster_client.cpp line being exercised. * `tests/test_resp_response_fuzzer.py` -- RLTest harness that runs memtier briefly against the mock for each fixture and asserts no fatal signal, no crash needle in stderr (`Aborted`, `Segmentation fault`, `AddressSanitizer`, ...), and no hang inside a 15s per-fixture budget. All 11 in-tree fixtures PASS on current master. The `cluster_slots_malformed` cluster-mode exercise *crashes* memtier with SIGSEGV in `cluster_client::handle_cluster_slots`; that fixture is skipped with a TODO referencing follow-up #417 so CI stays green. Framing: this is defensive client hardening, not an attack tool. Fixtures live in-tree, are reviewed during normal code review, and the pass criterion is "report and exit cleanly, never crash" -- the same contract the input-side parsers already have after #405. Fixes #409 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
fcostaoliveira
added a commit
that referenced
this pull request
Jun 1, 2026
…crash
Adds .github/workflows/soak-nightly.yml plus seven RLTest scenarios under
tests/soak/ that exercise memtier_benchmark in regimes PR-time CI never
hits: long duration, giant payloads, high concurrency, reconnect churn,
cluster topology turbulence, retry storms and lossy networks.
Total budget 60 minutes, scheduled at 02:17 UTC (cron '17 2 * * *') plus
workflow_dispatch. Build job uploads a release artifact; soak job runs
the matrix in fail-fast: false so a single regression doesn't mask the
others.
Per-scenario oracles:
S1 long_run_memory 30 min, RSS slope < 2 MB/min over the run
S2 large_payloads regen 20 MB + 100 MB monitor lines (NOT committed),
no SIGSEGV / no "stack smashing detected", server
STRLEN matches the blob -- direct regression guard
for PR #405 / issue #404
S3 high_concurrency 32t/256c, max fd count < 4*t*c, steady-state slope ~0
S4 connection_churn CLIENT KILL TYPE normal every 30s, survives all
rounds with --reconnect-interval=10
S5 cluster_turbulence 3-master + 3-replica, CLUSTER FAILOVER at t+120s,
CLUSTER SETSLOT MIGRATING at t+300s, exits with
cluster_state:ok
S6 retry_storm Python RESP shim returning 80% -ERR / 20% +OK,
peak RSS < 500 MB, peak CPU < 200%
S7 slow_network tc netem 200ms +/- 20ms, 1% loss; sudo-with-skip
wrapper so non-root sandboxes don't fail the suite
All scenarios honour MEMTIER_SOAK_TEST_TIME (and similar) env knobs so
the harness can be smoke-tested locally in seconds; CI runs the full
durations.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2 tasks
fcostaoliveira
added a commit
that referenced
this pull request
Jun 2, 2026
…443) Both were "temporary until #405 lands" guards added by PR #422. PR #405 (heap-vector fix for split_command_to_args) has been merged for weeks. The stale defaults meant the very regression path the fuzzer was built to cover -- multi-MB monitor lines -- was never actually exercised in the nightly run. Lifting the guards restores the intended coverage. Refs: 2.4 review #21 (Review 8). Co-authored-by: Claude Sonnet 4.6 <[email protected]>
fcostaoliveira
added a commit
that referenced
this pull request
Jun 2, 2026
Comprehensive notes covering 153 commits since 2.3.1: - 3 security advisories (#405, #415, #425) - 5 major features (--realtime-latencies, --retry-on-error, --transaction, --command-miss-tracking, --connection-stage-timeout) - Cluster gains: monitor-input route-then-stage, MGET slot-aware - 12 breaking-fail-fast changes (B1-B12) — all reject inputs 2.3 silently accepted and then crashed/hung on - JSON additions (strictly additive) - Testing & CI investment summary - Perf parity confirmed (no regression vs 2.3.1) - Known divergences Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #404
TL;DR
`arbitrary_command::split_command_to_args()` at `config_types.cpp:520` was declaring `char buffer[command_len]` on the stack. With `--monitor-input` replays the function is called per request from worker threads, so any captured MONITOR line larger than the worker's stack (default 8-12 MB on Linux) blew the stack the moment the picker selected it — SIGSEGV or `*** stack smashing detected ***`. The crash handler then often re-crashed in `_dl_fixup` because the stack was already corrupted, which is why the typical bug report was truncated.
Reproduction
Real 77 MB MONITOR capture containing one ~20 MB `HSET` (gzipped blob in the value):
```
memtier_benchmark -s host -p port -t 4 --clients 50 --pipeline 1
--monitor-input=replay.txt --command="monitor_line@" --requests=1000
```
Reproduces on current master (`15dae38`) and on the 2.3.1 release.
Crash path
```
shard_connection::fill_pipeline (shard_connection.cpp:1007)
-> client::create_arbitrary_request (client.cpp:396)
-> arbitrary_command::split_command_to_args (config_types.cpp:520) <- SEGV / canary trip
```
The fix
Replace the VLA with a `std::vector` so the scratch buffer lives on the heap and the stack-size dependency is gone. The function runs once per request — one heap allocation per call is a fair trade for removing an attacker-controlled stack allocation.
Test plan
`tests/test_monitor_input.py::test_monitor_input_large_line_no_stack_overflow` generates a single `"SET" "regression_key" "<16 MiB blob>"` MONITOR line, runs memtier with `--monitor-input` + `--command="monitor_line@"`, and asserts:
Locally I verified the test:
The test is bounded to standalone (`env.skipOnCluster()`) because `--monitor-input` doesn't support cluster mode, matching the other tests in that file.
🤖 Generated with Claude Code
Note
Low Risk
Small, localized change in per-request argument parsing with a targeted regression test; removes attacker-controlled stack allocation rather than altering auth or data semantics.
Overview
Fixes a stack overflow when replaying large
--monitor-inputlines:arbitrary_command::split_command_to_args()no longer uses a variable-length arraychar buffer[command_len]on the worker stack (which could exceed typical 8–12 MB thread stacks for multi‑MB MONITOR values). The token scratch buffer is now astd::vector<char>on the heap, withcommand_argbuilt frombuffer.data().Adds
test_monitor_input_large_line_no_stack_overflow, which replays a singleSETwith a 16 MiB value via__monitor_line@__and checks memtier exits cleanly (nostack smashing detected), plusSTRLENon Redis matches the payload.Reviewed by Cursor Bugbot for commit 4d4e0fc. Bugbot is set up for automated code reviews on this repo. Configure here.