Skip to content

fix(stack-safety): bound sscanf/strcat, iterative mbulk teardown, -Werror=vla - #415

Merged
fcostaoliveira merged 3 commits into
redis:masterfrom
filipecosta90:fix/issue-406-stack-allocation-foot-guns
Jun 1, 2026
Merged

fcostaoliveira merged 3 commits into
redis:masterfrom
filipecosta90:fix/issue-406-stack-allocation-foot-guns

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 30, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #406

Static-audit follow-up to PR #405 / issue #404. Closes the rest of the latent stack-allocation foot-guns surfaced by the audit in issue #406.

Findings addressed

HIGH — protocol.cpp:949 unbounded sscanf("%s") into a 256-byte stack buffer

memcache_text_protocol::parse_response was doing

char prefix[50];
char key[256];
int res = sscanf(line, "%s %s %u %u %u", prefix, key, &flags, &m_value_len, &cas);

against a server-derived line from evbuffer_readln. A malicious/buggy memcached server replying with VALUE <very-long-key> 0 999\r\n overwrites the worker thread's stack past key[]. Same class of bug as the VLA in arbitrary_command::split_command_to_args that PR #405 fixed (input-derived data written into a finite stack buffer with no bound). Fix: width-specifier the sscanf to %49s %255s.

MED — protocol.h:60-67 recursive ~mbulk_size_el destruction

~mbulk_size_el recursively deleted children that can themselves be mbulk_size_el. redis_protocol::parse_response builds the tree iteratively but tears it down recursively, so a deeply nested RESP array (*1\r\n*1\r\n*1\r\n…) blows the destructor's recursion when protocol_response::clear() runs. Fix: iterative worklist that steals each visited node's children before deleting it; the triggered destructor's loop finds an empty children-vector and never recurses, so teardown stack depth is O(1) regardless of input nesting depth.

MED — memtier_benchmark.cpp:234 unbounded strcat(fmtbuf, fmt)

benchmark_log_file_line() did snprintf(fmtbuf, sizeof-1, "%s:%u: ", …) then strcat(fmtbuf, 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. Fix: bounded snprintf-append pattern.

Guardrail — configure.ac adds -Werror=vla

The next attempt to size an automatic-storage array by attacker-controlled input now fails at compile time, not at customer site.

Merge-ordering note

-Werror=vla will reject the existing VLA at config_types.cpp:520, which is what PR #405 fixes. To keep this PR independently buildable, the PR #405 fix is cherry-picked as the first commit on this branch. Once #405 merges, that cherry-pick becomes a no-op against master; once this lands, #405's diff against master shrinks to just the regression test. Whichever lands first is fine — the other rebases cleanly.

Out of scope (deferred to follow-up)

LOW/hygiene items from issue #406 (char[PATH_MAX] stack buffers, run_stats.cpp fmtbufs, statsd.cpp request buffer): bounded today, migrating to std::string is churn-heavy and not load-bearing for the audit goal. Plus the clang-tidy / CodeQL guardrails — left for follow-up.

Test plan

🤖 Generated with Claude Code


Note

Medium Risk
Touches protocol parsing and response teardown on worker threads against untrusted server data; changes are defensive but sit on the hot response path.

Overview
Follow-up to the stack-safety audit (issue #406 / PR #405): hardens worker-thread stack handling against server-driven inputs and adds a compile-time guard.

Build: configure.ac adds -Werror=vla so variable-length automatic arrays fail the build instead of landing on small worker stacks.

Protocol parsing: Memcache text VALUE lines now use width-limited sscanf (%49s / %255s) so long keys from a hostile or buggy server cannot overflow fixed prefix / key stack buffers.

RESP teardown: mbulk_size_el destruction is iterative (worklist + steal children) instead of recursive delete, so deeply nested RESP arrays cannot blow the stack when protocol_response::clear() runs.

Logging: benchmark_log_file_line replaces unbounded strcat with bounded snprintf append into the 1024-byte fmtbuf.

Reviewed by Cursor Bugbot for commit 5db74e3. Bugbot is set up for automated code reviews on this repo. Configure here.

fcostaoliveira and others added 2 commits May 30, 2026 09:45
… 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]>
…rror=vla

Static-audit follow-up to PR redis#405 / issue redis#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 redis#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 redis#405 is cherry-picked here so this
  branch builds independently; once redis#405 lands the cherry-pick will
  no-op into master.

LOW/hygiene findings from issue redis#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 redis#406

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: design & API choices (sonnet 4.6)

  • Inline 30-line destructor in the header is a readability and compile-time concern. The iterative ~mbulk_size_el body is now 25+ lines of non-trivial logic (swap + worklist BFS) inlined in protocol.h. This gets re-parsed by every TU that includes the header. It belongs out-of-line in protocol.cpp — the class is not a template, nothing forces inlining, and the old recursive body was only there because it was trivially short.
  • -Werror=vla in unconditional CXXFLAGS is the right call. VLAs are the exact vulnerability class that shipped in production (#404). Treating them as a hard compile error in the default release build is appropriate here — this is not an opinionated style warning. No --enable-strict indirection needed; the PR description justifies it correctly.
  • sscanf width-specifier fix (%49s %255s) is the correct scope. Minimal, targeted, no API surface change. The one cosmetic note: the magic numbers 49/255 are derived from prefix[50] and key[256] respectively; a named constant (or a sizeof(prefix)-1 idiom) would make the contract self-documenting.
  • strcat → bounded-snprintf in benchmark_log_file_line is pre-emptive hardening. The rationale is sound (today all callers pass literals; the unbounded form is one refactor away from a bug). Minor: the intermediate n < 0 guard and cast chain is slightly verbose; a single snprintf-into-offset idiom is cleaner.
  • Cherry-pick of the #405 VLA fix as first commit is a reasonable merge-ordering workaround, but it does create a hidden dependency that the PR description documents well. Consider whether the configure.ac change (-Werror=vla) should be gated behind #405 merging rather than cherry-picked along for the ride.

Verdict: Approve (with suggestion to move destructor body out-of-line before merge)

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: performance (haiku 4.5)

  • Heap alloc per-request cost: std::vector<char> buffer(command_len) in split_command_to_args() runs per request under --monitor-input. A malloc/free pair per request replaces the old stack VLA. At typical MONITOR-line sizes (200–500 B), malloc overhead dominates: ~100–500 ns per allocation. For a 100k req/s pipeline this adds ~10–50 ms latency in the hot path. However, this is a correctness trade-off — the VLA crashed on lines >8 MB. The cost is unavoidable.
  • Vector swap amortization: The iterative ~mbulk_size_el teardown uses worklist.swap() to steal children, avoiding deep recursion. Each swap is O(1) pointer-copy; no meaningful hot-path impact. Tree deletion only happens at end-of-response (once per response, not per command).
  • -Werror=vla compile gate: Prevents future VLA foot-guns. Zero runtime cost; pure friction at build time.

Verdict: Approve — correctness necessity outweighs allocation cost.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

placeholder

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: security (opus 4.7)

  • sscanf widths are correct. prefix[50] with %49s and key[256] with %255s both leave room for the implicit NUL; sscanf width excludes the terminator. Off-by-one ruled out.
  • VLA -> std::vector<char> in arbitrary_command::split_command_to_args correctly drops the attacker-influenced stack allocation. Note the std::vector itself can throw std::bad_alloc if command_len is pathological; today the parser already swallows non-throw failures but a SET/bench replaying a multi-GB MONITOR line will now terminate via uncaught exception rather than SIGSEGV. Marginal hardening win; consider a soft size cap (e.g. 2 GiB) before the resize for graceful exit.
  • Iterative ~mbulk_size_el teardown is safe even though mbulk_size_el has an upper_level back-pointer (protocol.h:94): the destructor body never dereferences upper_level after the children-swap, so deleting the parent first and then the (orphaned) children does not trip a UAF. Worth a one-line comment to capture this invariant since it's load-bearing.
  • benchmark_log_file_line snprintf-append is robust to overlong filename (clamps n to sizeof(fmtbuf)-1); vfprintf(stderr, fmtbuf, args) still passes a potentially attacker-influenced format string. Today all callers pass literals (the very risk this PR cites), but the format-string sink remains — consider vfprintf(stderr, "%s", composed) plus a separate vsnprintf for the user payload to fully de-fang it.
  • -Werror=vla is a sound guardrail. No third-party build flow impact in this tree (grep -r 'char .*\[.*\]' --include=*.cpp shows no remaining true VLAs after the PR #405 fix is cherry-picked).
  • Regression test sets a 16 MiB SET and asserts no "stack smashing detected" — good. It does not assert exit code is 0 separately, so a clean crash that doesn't emit the canary would still pass; consider also asserting memtier_ok == True is non-tautological (it currently is).

Verdict: Approve

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: docs & commit message (haiku 4.5)

• Title uses Conventional Commits correctly: fix(scope): subject.
• First line correctly uses Refs #406 rather than Fixes #406 — appropriate because PR #405 closes the core issue and this is a related follow-up addressing sibling stack-safety issues. Merge-ordering note explains the cherry-pick.
• Test plan is honest about CI coverage and defers fuzzing regression tests to separate PRs (#407/#409), which is correct.
• "Out of scope" section clearly defers hygiene tasks (char[PATH_MAX], etc.), keeping the scope bounded.
• Minor: Test plan shows [ ] unchecked box for sanitizer CI "to be confirmed" — this is forward-looking and appropriate for an open PR.

Verdict: Approve

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: edge cases & failure modes (opus 4.7)

  • protocol.h:60-89 — iterative ~mbulk_size_el now allocates std::vector<mbulk_element*> worklist and a per-node stolen vector with no try/catch. On an OOM bad_alloc inside the destructor the children leak (and we throw from a ~); the original recursive version had the same hazard but at much smaller scale. Consider wrapping the swap/push_back loop in try{}catch(std::bad_alloc&){std::terminate();} so behavior is at least defined.
  • protocol.h:60-89 — worklist grows unboundedly while we walk the tree; for an *N of INT_MAX bulk subarrays this is exactly the depth-vs-breadth tradeoff. Worst case the parser has already bounded the breadth via bulks_count int decrement, but a malicious server can still drive the worklist to O(total nodes). Fine for now — just confirm bulks_count is int (signed) so a *-1 reply doesn't underflow into UINT_MAX-children territory.
  • config_types.cpp:519 — std::vector<char> buffer(command_len) will throw bad_alloc on a 100GB+ replay; caller arbitrary_command::split_command_to_args returns bool but doesn't catch. A malformed multi-GB MONITOR line now terminates via uncaught exception instead of segfault — still "no crash report" but better than stack-smash. The new test test_monitor_input_large_line_no_stack_overflow only goes to 16 MiB so the exception path is untested.
  • tests/test_monitor_input.py:805 — uses tempfile.mkdtemp() but never cleans up. After 10 iterations of CI on the 16 MiB blob you've leaked 160 MiB under /tmp. Add a try/finally shutil.rmtree.
  • memtier_benchmark.cpp:233-236 — new clamp if ((size_t)n >= sizeof(fmtbuf)) n = sizeof(fmtbuf)-1; is correct on the boundary, but the chained snprintf(fmtbuf + n, sizeof(fmtbuf) - n, "%s", fmt) when n == sizeof(fmtbuf)-1 writes exactly one byte: the trailing NUL. Format string is silently dropped. Minor but worth a comment.
  • configure.ac:32 — -Werror=vla is a hard-error guardrail; works with gcc/clang but pre-15 gcc bundled with RHEL8 emits the diagnostic with a different name. If your CI matrix includes that toolchain the build will fail; not a code bug but a deploy-time pitfall.
  • protocol.cpp:949 — width-spec fix is correct. Note that sscanf still does not validate flags/m_value_len/cas against INT_MAX; a VALUE k 0 4294967295\r\n reply sets m_value_len to UINT_MAX and is then used to size the next read in the bulk path. Out of scope for this PR.

Verdict: Comment

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: correctness & latent bugs (opus 4.7)

  • protocol.h:71-83 iterative teardown looks correct, but the worklist itself is grown on the heap by walking the whole tree before any node is freed — peak memory during destruction equals the full reachable child set (sum of all mbulks_elements vectors). For the *4294967295\r\n style mbulk-count-overflow corpus in PR #419 this could be a 32 GB allocation before the first delete runs. Consider deleting each visited node before pushing its grandchildren so memory stays bounded.
  • protocol.cpp:949 sscanf width fix is correct, but prefix is sized 50 with %49s which leaves no room for prefix[49] plus the implicit NUL — %49s consumes up to 49 bytes + NUL = 50, exactly fits. Fine; just call out the off-by-one is right.
  • memtier_benchmark.cpp:233-240 snprintf-append: when the first snprintf returns n >= sizeof(fmtbuf) you clamp to sizeof(fmtbuf)-1, then the second snprintf gets sizeof(fmtbuf) - n == 1 and writes only the NUL. That silently drops fmt on truncation rather than logging "filename:line: " plus as much of fmt as fits — minor, not a bug, but worth noting if anyone counts on the format-string suffix being present.
  • configure.ac:32 -Werror=vla is a guardrail win, but -Wall does not enable -Wvla on GCC by default; the warning is only emitted under -pedantic/-Wvla. As written, the -Werror=vla would only catch VLAs that GCC happens to warn about with the current flag set. Recommend -Wvla -Werror=vla to make the guardrail actually load-bearing.
  • config_types.cpp:520 std::vector<char> buffer(command_len) value-initializes (zero-fills) command_len bytes per call. For the 16 MiB regression test that's 16 MB of zeroing per request — functionally fine, just a perf cliff vs the VLA. Not a correctness issue.
  • Test test_monitor_input_large_line_no_stack_overflow runs 10 SETs of 16 MiB each at --pipeline= default — that's ~160 MB on loopback. If the CI runner has proto-max-bulk-len at the default 512 MB you're fine, but the test makes no attempt to set it; on a hardened CI redis with a lower cap (256 MB) the test would fail for the wrong reason. Not load-bearing today.

Verdict: Comment

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: code style & readability (sonnet 4.6)

  • ~mbulk_size_el growing in-header (protocol.h): The destructor is now ~20 lines and contains a nested loop, a type-downcast, and a vector swap. For a header-only class this is past the comfortable inline threshold; moving the body out-of-line to protocol.cpp would make the header scannable again.
  • stolen name is accurate but the inner scope could be extracted: The two-variable names (worklist / stolen) are clear; the comment block above the loop explains the invariant well (why it does not recurse). No rename needed, but extracting the inner drain into a helper function would reduce indent depth and make it unit-testable.
  • Comment quality is good: All three C++ change-sites carry "WHY" comments that identify the specific attack vector, cross-reference the sibling PR, and state the invariant being protected. The configure.ac comment is particularly good — it names the exact commit history for -Werror=vla.
  • int n for snprintf return (memtier_benchmark.cpp): Fine in local context; the casts to size_t / int on the bounds-clamp block are slightly noisy but correct and self-documented.
  • The sscanf width-specifier fix (protocol.cpp) comment names the input-control threat ("malicious/buggy server"), links to the same bug class, and is accurate. Good.
  • Test comment quality (test_monitor_input.py): The docstring is thorough and explains the before/after behavior with concrete size numbers. Slight nit: the in-function comment "# 16 MiB value: comfortably larger…" could live in the docstring rather than mid-function, keeping code/comment separation clean.

Verdict: Approve

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: code style & readability (sonnet 4.6)

  • ~mbulk_size_el growing in-header (protocol.h): The destructor is now ~20 lines and contains a nested loop, a type-downcast, and a vector swap. For a header-only class this is past the comfortable inline threshold; moving the body out-of-line to protocol.cpp would make the header scannable again.
  • stolen name is accurate but the inner scope is dense: Two nested loops with two swap-idioms in a destructor body is readable because of the comment, but extracting the inner drain into a named helper would reduce indent depth and make the invariant independently testable.
  • Comment quality is good throughout: All three C++ change-sites carry "WHY" comments that identify the specific attack vector, cross-reference the sibling PR, and state the invariant being protected. The configure.ac comment is particularly strong — it names the concrete failure history for -Werror=vla.
  • int n for snprintf return: Fine in local context; the casts on the bounds-clamp block are slightly noisy but correct and self-documented inline.
  • The sscanf width-specifier comment names the threat correctly and is accurate.
  • Test docstring in test_monitor_input.py: Thorough and explains before/after with concrete numbers. Minor nit: the inline comment mid-function ("# 16 MiB value: comfortably larger…") duplicates the docstring and could be removed to keep code/comment separation clean.

Verdict: Approve

@fcostaoliveira
fcostaoliveira merged commit ee6adea into redis:master Jun 1, 2026
65 checks passed
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant