Code Injection

ID

python.cache_injection

Severity

critical

Resource

Injection

Language

Python

Tags

CWE:913, NIST.SP.800-53, OWASP:2021:A3, PCI-DSS:6.5.1

Description

Improper use of dynamic or unvalidated input in cache key construction can lead to cache injection, resulting in denial of service, information leakage, or incorrect application behavior.

Rationale

Cache injection vulnerabilities occur when user-controlled input is used directly to construct cache keys without proper validation or sanitization. In Python applications, this often appears when using libraries like Flask-Caching, Django’s cache framework, or low-level cache clients like redis-py or memcached.

The risk is that attackers can manipulate cache behavior by injecting unexpected or malicious data into cache keys. This can cause: - Cache poisoning, where attackers control the content returned to other users. - Cache bypass, where sensitive data is retrieved or stored under attacker-controlled keys. - Denial of Service (DoS), where excessive unique keys flood the cache storage.

Example of vulnerable cache key usage (manual caching logic):

import pylibmc
from flask import Flask, request

app = Flask(__name__)
mc = pylibmc.Client(["127.0.0.1"], binary=True)

@app.route("/profile")
def get_profile():
    user_id = request.args.get("user_id")  # Unsafe input
    key = f"profile:{user_id}"             # Vulnerable: unvalidated input in cache key

    data = mc.get(key)
    if data is None:
        data = load_user_profile(user_id)
        mc.set(key, data, time=300)
    return data

In this example, the cache key is built directly from user input. An attacker could craft requests with many different user_id values to bypass caching or poison the cache content.

Remediation

To mitigate this vulnerability:

  1. Validate and sanitize input used in cache keys.

  2. Limit possible key values via whitelisting.

  3. Avoid untrusted input in keys when possible. If dynamic values must be used, consider applying hash functions or mapping to a controlled namespace.

  4. Monitor cache usage and apply rate limits to prevent abuse or cache flooding.

By taking care in how cache keys are constructed, especially when user input is involved, you prevent attackers from degrading performance or accessing unintended data.

Configuration

The detector has the following configurable parameters:

  • sources, that indicates the source kinds to check.

  • neutralizations, that indicates the neutralization kinds to check.

Unless you need to change the default behavior, you typically do not need to configure this detector.

References