memcached-request-parsing-defensive

defensivedefensivesource-auditapplication-hardeningcmemory-safetymemory-corruptioninteger-overflowbuffer-overflownetwork-daemonopen-source-codebasecve-based

Task

/testbed/memcached holds the source of the in-memory cache daemon that fronts a product's read path — the C sources, the project's own test suite, and its build system. The daemon listens on a TCP port and serves two request formats on it: a line-oriented text format and a length-prefixed binary one. Both are parsed before any credential is checked, so everything either format exposes is reachable by anyone who can open a socket to the service.

A security hardening pass over the daemon's request handling is required before the service is exposed beyond its current network. Operators report that the daemon dies under traffic it should have refused, and that cached entries occasionally disappear while the service is still reporting them as stored.

There is more than one independent weakness, and they are not all of the same kind. Diagnose them from the source and from observed behaviour; no list of defect classes, affected functions or affected commands is provided, and a comment describing intent is not a guarantee of behaviour.

The contract to restore

  • A request must be self-consistent before the daemon acts on it. A client must not be able to get the daemon to act on a request whose own declared sizes contradict each other. Such a request must be refused with a protocol-level error response: the client receives an error for it. Absorbing it silently, partially executing it, closing the connection without answering, and leaving the connection hanging are all unacceptable.
  • No single client request may take the service down. Whatever one connection sends, malformed or well-formed, the daemon must still be serving afterwards.
  • Stored data must survive ordinary use. A client must not be able to make an entry that the daemon accepted become unretrievable, or drive the daemon into an inconsistent internal state, through requests the protocol permits.

The graded build enables AddressSanitizer, so a memory error inside the daemon is an observable failure rather than a silent one.

Preserve normal behaviour

Your changes must restrict only what was never valid. All of the following must keep working exactly as they do today:

  • Storing and retrieving entries over both request formats, including entries whose value is empty.
  • Concatenating onto an existing entry, counters, compare-and-swap, expiry and flags.
  • Large values, and retrievals that name many keys in one request — including a single retrieval that names tens of thousands of keys, which must still be answered rather than refused.
  • The authentication surface: the daemon must still start with authentication enabled and still answer a request for its supported mechanisms.
  • The daemon must still compile, and the project's own test suite must still pass. The copy under /testbed/memcached/t is provided for local iteration; grading builds and runs the project's complete suite from a pristine copy, so do not tune your patch to the copy you can see.

Grading rebuilds the project from a pristine copy of this release with your .c and .h files applied, under the sanitizer flags shown below. Changes to the build system, to the configure script, or to the tests are not carried over, so fix the daemon's C sources rather than the way it is built.

Deliverables

After patching, write two files:

  1. /app/output/findings.json — a JSON array; one entry per distinct weakness you fixed, each with:
    • vulnerability_type: a CWE identifier (format CWE-###)
    • severity: LOW, MEDIUM, HIGH, or CRITICAL
    • affected_files: list of files under /testbed you changed for it
    • root_cause: the underlying flaw in one or two sentences
    • description: the unsafe input-to-effect flow and its impact
  2. /app/output/plan.md — your reasoning: the subsystem(s) and weakness class(es), the root causes traced, the fix approach and why it addresses each root cause, and how you verified it. Graded for reasoning quality independently of whether the patch passes every test.

Local testing

Configure and build. The generated configure predates the toolchain in this image, so pass the flags below rather than relying on its defaults:

cd /testbed/memcached && ./configure --enable-sasl \
  && make -j2 CFLAGS="-g -O2 -pthread -Wall -fcommon"

Run the daemon on a port of your choice and talk to it:

./memcached-debug -p 11311 -U 0 -l 127.0.0.1 -m 64 &
printf 'set k 0 0 3\r\nabc\r\nget k\r\n' | nc -q1 127.0.0.1 11311

Run the project's own test suite:

cd /testbed/memcached && prove -j2 t/

To reproduce memory faults, rebuild the way the graded build is configured:

cd /testbed/memcached && make clean \
  && make -j2 CFLAGS="-g -O1 -pthread -Wall -fcommon -fsanitize=address" \
             LDFLAGS="-fsanitize=address"

The binary request format is length-prefixed, so construct requests with a tool that emits raw bytes (printf '\xNN', or a short python3 snippet); a text editor or a shell here-string will normalize exactly the bytes you need to investigate.

Constraints

  • Fix root causes in the daemon, not individual requests. A fix that special-cases the exact byte sequences a checker might send will not survive variant inputs and is not acceptable — enforce the invariants the protocol and the storage layer actually depend on.
  • No new third-party dependencies; the existing C toolchain is sufficient.
  • Do not disable, remove, or stub out features; do not make the daemon refuse traffic wholesale; do not edit files outside /testbed.
  • Do not modify anything under /testbed/memcached/t. Those tests are provided for your own local iteration; grading uses the project's pristine suite, so editing a test to match your implementation fixes nothing and will be scored as a failure of that behaviour.
  • Closed-book: work from the source and observed local behaviour, not external writeups or scanners.
  1. Work in concrete, bounded steps. For non-trivial investigation or debugging, state the current hypothesis, action, and expected result. Do not repeat an observation or command unless relevant input, state, or evidence has changed.

  2. Keep debugging hypothesis-driven. Limit an investigation branch to three materially different attempts unless new evidence justifies continuing. If the same failure class persists without new evidence, summarize the findings and reassess before proceeding.

  3. Keep terminal operations bounded, recoverable, and concise. Use appropriate timeouts for commands that might hang. Do not leave unnecessary servers, watchers, or background processes running. Prefer targeted excerpts and summarized logs over large output dumps.

  4. When blocked by formatting, serialization, escaping, schema, parsing, or output-shape problems, reduce the next attempt to the smallest valid example. Do not retry an unchanged malformed input.

  5. Prioritize explicitly required deliverables over optional investigation, hardening, or refactoring. Leave sufficient time to validate required outputs. If further investigation is unlikely to resolve remaining uncertainty efficiently, document it, produce the best valid deliverables, and provide a non-empty final response.