ASVS 5.0 V1.3.9 (Level 2) requires that content is sanitized before it is sent to memcache, to prevent injection attacks. The risk is highest in keys: the text protocol uses spaces and line breaks as delimiters, so a key built from user input can smuggle in extra commands.
Why it matters
A key such as user: plus a user value, where the value contains \r\nset admin 0 0 1\r\n1, can make some clients send a second command. The result might overwrite a cached session or poison a cached page that other users receive. Cache poisoning is quiet and hits many people.
How to implement it
Never put raw user text in a key. Hash it, or validate against a strict pattern.
import hashlib
def cache_key(prefix: str, user_value: str) -> str:
digest = hashlib.sha256(user_value.encode("utf-8")).hexdigest()
return f"{prefix}:{digest}" # fixed length, hex only: no spaces, no line breaks
Also: use a maintained client that rejects keys containing whitespace or control characters, prefer the binary protocol, and restrict network access to the memcache port. Serialize values with a data format such as JSON. Avoid native object serialization, because poisoned values then become a deserialization problem.
How to test it
Use a test value containing \r\n and a space as part of every cached lookup. The client should raise an error or the key should be hashed to hex. Check by listing keys on a test server that no unexpected key such as admin appears.
Common mistakes
- Trusting a client library to filter keys without testing it.
- Keys longer than 250 bytes that are silently truncated and collide.
- Caching responses keyed by a user supplied header.
Quick check
Why hash user values used in a key?
A hex digest has no spaces or line breaks and a fixed length, so it cannot inject protocol commands.