Cache poisoning

Source-based lab reference

SecureBank builds a shared page from an HTTP header, then stores it under one Redis key. A later request can receive that page even when it sends no such header.

Web cache poisoningFlaskRedisUnkeyed inputStatic review

This reference is based on the supplied Flask source, Docker configuration, README, technical notes, and exploitation guide. It explains the intended local lab without building or launching it.

One request can change the shared response

The homepage reads X-Forwarded-Host when Redis has no cached page. The value changes the Support Portal link and can trigger a hidden flag banner. Flask stores the complete HTML under the fixed key index_page for 60 seconds. Since that key does not vary with the header, a later visitor can receive the first visitor's page.

  1. RequestX-Forwarded-Host: …Checked only on a cache miss
  2. Page generationhttp://{host}/supportHeader influences returned HTML
  3. Redis writeindex_page · 60 secOne shared cache key
  4. Next visitorX-Cache: HITReceives stored page as-is
Flow reconstructed from Cache-Poisoning/web/app.py. Expected output is source-derived; no request was sent.

Two objectives, several weaknesses

Find the exposed build flag

The /status endpoint reads a file and returns it in the build_id field.

Understand the cache flaw

Compare the response inputs with the cache key and test whether a separate request reuses the changed page.

Trace the special host

A configured host value causes a secret flag banner to be included on a fresh cache miss.

Review the surrounding access controls

The diagnostic endpoint trusts a client-set cookie and exposes a small Redis command allowlist.

Scope and isolation

This intentionally vulnerable lab belongs in an isolated environment you control. Compose publishes "5000:5000" and "6379:6379" without a host IP; Docker normally binds those ports on all host interfaces, not just localhost. Before any future launch, restrict access, for example with loopback mappings "127.0.0.1:5000:5000" and "127.0.0.1:6379:6379", plus suitable network controls. This HTML has no connection to Flask or Redis, and this review did not change Compose or launch either service.

Two findings need separate proof

The lab exposes one flag through /status and describes a second in the cache-generated page. Reading the first value does not show cache poisoning. For the second path, show both the special response on a cache miss and reuse of that stored body by a later request that omits the special header.

How the cache works

Checked against app.py

The key mismatch is explicit: the page varies by a request header, while Redis always looks up the same string.

Read order matters

The route checks Redis before reading X-Forwarded-Host. If a value is cached, the route returns it immediately and marks the response X-Cache: HIT. Only an empty cache reaches the host lookup, HTML generation, and setex() write.

web/app.py lines 19–20 and 242–265 · condensed route excerpt
CACHE_KEY = "index_page"
CACHE_TTL = 60

cached_page = redis_client.get(CACHE_KEY)
if cached_page:
    response = make_response(cached_page)
    response.headers['X-Cache'] = 'HIT'
    return response

forwarded_host = request.headers.get(
    'X-Forwarded-Host', 'support.securebank.local')
show_secret_flag = (
    forwarded_host.lower() == SECRET_POISON_HOST.lower())
page_html = generate_page_html(
    forwarded_host, show_secret_flag=show_secret_flag)
redis_client.setex(CACHE_KEY, CACHE_TTL, page_html)
response = make_response(page_html)
response.headers['X-Cache'] = 'MISS'
return response

Conditions for poisoning

  • The cache entry must be absent, expired, or cleared so the request reaches the generation code.
  • The chosen input must affect a response that the application stores. Here, the host is interpolated into the Support Portal URL and the special host toggles the flag banner.
  • The next request must map to the same cache entry. Here, every homepage request uses the same Redis key.
  • The page must be delivered to another visitor before expiry or cache replacement. The configured TTL is 60 seconds.

A hit skips the header check entirely. Sending the special header while a non-special page is already cached will not regenerate the page; first ensure the key is empty. A successful reflected header on a miss alone also does not demonstrate propagation—check a second request without that header.

Two different cache layers

This lab's vulnerability is in application-managed Redis storage: Python explicitly reads and writes index_page. An HTTP Vary response header tells compliant HTTP caches which request headers affect response selection. It does not change this Python string key or Redis lookup. For this application cache, the key or the stored content logic must be fixed directly.

Trace the shared state across requests

Redis stateRequest headerRoute behavior from sourceEvidence to compare
Key absentDefault or ordinary hostGenerates the regular page, stores it for 60 seconds, returns X-Cache: MISS.Response body contains the chosen support host.
Key absentConfigured secret hostIncludes the second flag banner, stores that page, returns a miss.Banner appears in the miss response; this is the seed request.
Nonempty cached pageAny host, including a different oneReturns cached HTML with X-Cache: HIT; the current header is not inspected.Compare the later body with the stored miss response.
Key expired or clearedNext miss generates content againExecution returns to the generation path.The 60-second TTL and clear route bound persistence.

The check is actually if cached_page, so an empty stored string also follows the miss path. Normally the app stores a nonempty HTML document. Reflection on a miss is not enough to establish poisoning: a separate header-free request must reuse the changed body. Source review does not observe a real victim request.

TTL and concurrent misses

Redis SETEX writes the value and its expiry together. The 60 seconds start at that write; a hit only performs GET and does not renew the TTL. The page's displayed “TTL: 60s” is a constant, not a live countdown.

The full GET → generate → SETEX sequence is not atomic. The Dockerfile declares two Gunicorn workers with four threads each, so simultaneous misses can generate different pages and the last write wins. A clear request can also race with an in-flight miss that writes afterward. A reflected miss therefore does not guarantee that its exact body remains stored; verify the follow-up body promptly and record other traffic or invalidation.

A changed link is not a server-side fetch

The application interpolates the host into <a href="http://{support_host}/support">. It does not request that address, issue an HTTP redirect, or define a separate support-portal service. A visitor following a poisoned link is the link-manipulation impact, not demonstrated SSRF. The unescaped HTML attribute is an additional injection concern, separate from the cache key; no browser-side execution was tested.

Recon & access

Other issues in the lab

The challenge is broader than the cache key. Its status route, diagnostic cookie, Redis exposure, and cache-clearing route all matter to the intended flag path.

Endpoints from the Flask source

RouteBehavior in sourceSecurity observation
/Serves the Redis-cached dashboard; uses header on a missStatic shared key excludes the input reflected into HTML.
/statusReturns application metadata and reads /opt/flag1.txtBuild flag is exposed by an unauthenticated status endpoint.
/robots.txtLists hidden paths, including /admin/shellProvides route discovery hints; robots rules are not access controls.
/admin/shellRequires cookie exactly Admin=true; supports six Redis operationsAuthorization is entirely client-controlled; this is not an OS shell.
/cache/clearDeletes the page key through an unauthenticated GET requestPublic state change uses a safe/read-style HTTP method.

What the admin endpoint actually allows

The name “shell” is misleading. The code dispatches Redis calls for INFO, PING, KEYS, GET, DBSIZE, and TIME, not arbitrary OS commands. Cookie name Admin and value true must match exactly; command names are compared after .upper(). A request without that cookie receives the source-defined 403 response, but setting it is entirely client-controlled.

Compose publishes Redis on host port 6379 and seeds config:cache:secret_host and other sensitive-looking values. That Redis key is a discovery hint, not the value consulted by the flag branch: Flask compares the header with its environment-derived SECRET_POISON_HOST. Compose makes both agree at flag.securebank.internal. Changing only the Redis hint would not change Flask's comparison.

The host comparison lowercases both strings but does not strip whitespace or parse ports or comma-separated proxy lists. Case variants match; otherwise the received value must match the configured spelling. The Dockerfile runs the web process as appuser and sets both /opt/flag*.txt files to mode 0644; a non-root process can still read these deliberately exposed lab files.

Flag claims and source evidence

Compose's build arguments define both flag values. The Flask code reads flag one from /opt/flag1.txt for /status; the page generator reads flag two from /opt/flag2.txt only when the host comparison succeeds on a miss.

Reveal the two source-declared flags
FlagSource-declared valueWhere the source says it appears
1FLAG{r3c0n_1s_k3y_t0_succ3ss_4521}/status response, in build_id
2FLAG{p01s0n_th3_c4ch3_w1th_s3cr3t_h0st_7832}Generated homepage on a fresh cache miss with the configured secret host

These values are present in the supplied Compose build arguments. They are source-disclosed, not runtime-retrieved results from this review.

Documentation corrections

The README describes a portal on port 8080 and three containers, but the supplied Compose file defines only two services: web-app on port 5000 and redis-db on port 6379. Its quick-start directory name is also stale. The source and Compose file are the stronger evidence for this checkout.

Keep the two flag paths distinct

The routes form separate evidence trails. The first flag is read by the status handler into JSON. The second is read by the page-generation helper only when a cache miss reaches the configured host comparison. Name the route and source condition for each value.

SurfaceSource-level concernAccurate description
/statusBuild metadata includes a file-backed flag.Unauthenticated information disclosure, independent of the cache key.
/admin/shellAuthorization checks a caller-provided cookie; commands are allowlisted Redis operations.Broken access control over diagnostics, not arbitrary OS command execution.
Redis serviceCompose publishes port 6379 and seeds configuration data.Exposure in this supplied local configuration; do not assume equivalent reachability elsewhere.
/cache/clearUnauthenticated GET deletes shared page state.Unsafe state-changing route and lab convenience, not a production-safe design.
/One key stores HTML generated from an unkeyed request header.The cache-poisoning root cause analyzed in the mechanics section.

These issues can help a student discover the intended path, but they are not interchangeable. Document each weakness, its trust boundary, and the evidence connecting it to impact.

Study walkthrough

Reference commands only

Compare a cache miss with a later cache hit, then follow the documented flag path. The commands below are examples for the isolated local lab; this guide does not execute them.

Only run these requests against training services you started and control, with access restricted as described in the overview. lab-poison.invalid is a reserved example hostname, not a live attacker site. Keep other homepage traffic out of the miss-to-hit comparison and send the follow-up before the entry expires.

  1. Start the local services

    From the repository root, enter the lab directory and start its Compose services. The supplied configuration describes the target at port 5000 and Redis at 6379.

    Reference setup
    cd Cache-Poisoning
    docker compose up --build -d
  2. Read the public hints

    Inspect the status response and robots file. In the supplied source, the status JSON's build_id field is read from the first flag file; robots advertises the diagnostic route.

    Local reconnaissance
    curl -i http://localhost:5000/status
    curl -i http://localhost:5000/robots.txt
  3. Prove header reflection and reuse separately

    Clear the key, request a benign reserved host, then request the homepage without that header. Compare the X-Cache values and the Support Portal link.

    Local cache check
    curl -sS http://localhost:5000/cache/clear
    curl -i http://localhost:5000/ \
      -H 'X-Forwarded-Host: lab-poison.invalid'
    curl -i http://localhost:5000/

    Expected from source: first homepage response is a miss and includes the supplied host; the next request is a hit and reuses that stored page. The expected behavior has not been tested here.

  4. Find the configured secret host

    The documented route requires the exact client cookie Admin=true. The allowlisted GET operation can retrieve the seeded configuration value.

    Local diagnostic request
    curl -sS -b 'Admin=true' \
      'http://localhost:5000/admin/shell?cmd=GET&key=config:cache:secret_host'

    Compose seeds flag.securebank.internal in Redis and also sets it as SECRET_POISON_HOST.

  5. Observe the flag path on a fresh cache

    Clear the cache before using the special host; otherwise the existing page is returned before the header is inspected. Then request the page again without the header to see what the shared key contains.

    Documented lab sequence
    curl -sS http://localhost:5000/cache/clear
    curl -i http://localhost:5000/ \
      -H 'X-Forwarded-Host: flag.securebank.internal'
    curl -i http://localhost:5000/

    Docker Compose declares the expected second flag value. It is included in the page generator only when the secret host matches during a cache miss. No request was sent for this reference.

Stop the lab when finished

The supplied README documents docker compose down from the lab directory. This page does not start or stop containers.

Keep a compact evidence log

ObservationSupportsDoes not prove by itself
X-Cache: MISS with a reflected ordinary hostThe miss path generated a body using the supplied header.That a later request will receive it.
Header-free follow-up returns X-Cache: HIT and the same linkThe app reused stored HTML without reading the follow-up header.That a real third-party visitor received it.
Secret-host miss includes the second flag bannerThe configured comparison and flag-generation branch ran on a miss.That the page remained cached after its TTL.
/status contains the build valueThe separate status disclosure path is available in source.Anything about cache poisoning.

Record the response header and body together, note whether state was cleared or expired, and keep the two flag routes separate in the conclusion. The commands above are future local-lab examples only; they were not sent for this review.

Lessons & defenses

Design the cache boundary

Fix the mismatch at the layer that creates it, and reduce the number of inputs and secrets that can reach shared responses.

For the application cache

  • Do not trust arbitrary forwarded hosts. A trusted proxy must replace client-supplied forwarding headers; also prevent direct origin access from bypassing that proxy policy and accept only known hostnames.
  • Keep canonical URLs in configuration. If the support link is fixed, build it from a trusted setting rather than request headers.
  • Key legitimate response variants. If public content must vary by host, validate and normalize an allowlisted value before including it in the cache key. Merely keying every arbitrary header value preserves untrusted content and permits unbounded cache entries.
  • Do not store personalized or secret pages in shared Redis entries. Bypass both the shared lookup and write for sensitive routes, or partition authorized data by the correct identity and policy. HTTP private/no-store headers do not stop this application's explicit GET/SETEX calls.
  • Encode for the output context. Validate the intended URL and use an autoescaping template for HTML attributes; a correct cache key alone does not make interpolated markup safe.

A simpler public-page design

If every visitor should see the same support link, remove the request-controlled host and flag branch from the public generator. The existing single key can then hold one deliberately public variant. This sketch illustrates that choice, not a drop-in patch for the lab:

Public cache generation sketch · not the supplied implementation
SUPPORT_HOST = "support.example.invalid"  # trusted deployment setting

# On a public-page cache miss; no forwarded header or secret banner.
page_html = generate_page_html(SUPPORT_HOST, show_secret_flag=False)
redis_client.setex(CACHE_KEY, CACHE_TTL, page_html)

Keep authenticated data and status secrets out of this page, encode any other dynamic values, and invalidate old unsafe entries during rollout. A post-fix check should show that varied client forwarding headers cannot change the public link or the reused body.

For HTTP caches and infrastructure

RFC 9111 defines the HTTP cache model: the cache key includes at least the request method and target URI, and a response's Vary field can require matching nominated request headers. That mechanism applies to HTTP caches honoring the response. It does not automatically modify custom Redis keys inside an application.

Audit each caching layer separately: application Redis, reverse proxy, CDN, and browser cache may have different keys and policies. Remove unnecessary unkeyed inputs, disable caching for sensitive responses, and verify the cache behavior with a separate request that omits the crafted input.

For the surrounding endpoints

  • Use server-side authentication and authorization for diagnostic operations; never treat a client-chosen cookie value as an admin identity.
  • Expose only the minimum required Redis commands, and keep Redis private from host or untrusted network access.
  • Keep secrets out of public status metadata and shared cacheable HTML.
  • Make cache invalidation an authenticated state-changing operation using an appropriate method and CSRF protections.

Self-check

  • Can I name the exact Redis key and explain why the forwarded host is absent from it?
  • Can I walk through cache lookup before header lookup?
  • Can I distinguish a reflected miss response from later cache reuse?
  • Can I explain why Vary does not rewrite this application's Redis key?
  • Can I separate the /status flag from the cache-generated flag?
  • Can I describe what Admin=true actually authorizes in this source?
  • Can I explain why the route called “shell” is not an OS shell?
  • Can I state what remains unverified without a live request and a second client?

Review plan for a real deployment

Inventory every cache layer, record its key inputs, and identify headers used during response generation. In controlled staging, compare a cache miss with a separate request that omits the varied input; include expiration and invalidation in the record. Then review output encoding, proxy-header trust, authentication on diagnostics, Redis network exposure, and whether responses contain user-specific or secret data. Check each layer separately because application caches and HTTP caches follow different rules.

Further reading

Files & evidence

Provenance & limits

Keep the implementation details, documentation claims, and untested runtime behavior separate.

Files reviewed

FileRoleEvidence used here
Cache-Poisoning/web/app.pyFlask routes and page generatorFixed Redis key, TTL, header lookup order, HTML interpolation, flags, admin cookie, route behavior.
Cache-Poisoning/docker-compose.ymlService and seed configurationTwo services, published ports, flag build arguments, secret host, Redis seed keys.
Cache-Poisoning/web/DockerfileWeb image build instructionsFlag files, base image, runtime user, and process configuration.
Cache-Poisoning/README.mdStudent lab overviewObjectives, architecture claims, setup notes, and expected attack flow.
Cache-Poisoning/EXPLOITATION_GUIDE.mdWalkthroughDocumented reconnaissance and cache sequence.
Cache-Poisoning/LAB_INTERNALS.mdImplementation notesIntended vulnerabilities, endpoints, and mitigations.

Source reading map

Source areaQuestion answered
web/app.py: cache constants and index()Which key and TTL are used? Does the route return before reading the header? Which response marks a miss or hit?
web/app.py: page-generation helpersWhere does the forwarded host enter HTML, and what condition enables the flag banner?
web/app.py: status and diagnostic routesHow is flag one returned? What cookie and Redis command allowlist protect diagnostics?
web/app.py: clear and robots routesHow can cache state be cleared, and which paths are advertised to crawlers?
docker-compose.yml and web/DockerfileWhich services, ports, build arguments, environment values, and image files are declared?

Start with the mechanics excerpt for the cache path, then use the complete inert snapshots below for surrounding endpoints and deployment declarations. This keeps the other weaknesses distinct from the poisoning root cause.

Evidence boundary

  • Source-confirmed: a constant index_page key, 60-second TTL, cache lookup before header lookup, case-insensitive environment-host comparison on a miss, unescaped host interpolation, and explicit Redis writes.
  • Configuration-confirmed: two services, published ports 5000 and 6379, flag build arguments, matching environment/Redis hint values, declared non-root web user and readable flag modes, and concurrent Gunicorn workers/threads.
  • Documentation-reported: expected HTTP responses and successful attack outcomes; the flag values are also directly visible in Compose.
  • Not established here: image build success, running service state, live endpoint responses, cache timing or race outcomes, or successful retrieval of either flag.
  • Not performed: no supplied code, container, request, or lab service was run or tested.

Documentation mismatch

The supplied README describes a portal on port 8080 and three containers, while the supplied Compose file contains two services and no portal. This page follows the actual application source and Compose file for architecture details.

What “reviewed” means here

This standalone HTML is self-contained for reading and navigation. External references are links only. The source and configuration snapshots below are embedded as escaped, inert text, not executable lab files. The page does not launch a service or send lab requests.

Complete inert source snapshots

These collapsible snapshots preserve the supplied files as readable text for offline review. Expand only the files relevant to your question; no source, container, request, or lab is launched by this page.

Read Cache-Poisoning/web/app.py · complete original Flask application

This is inert text copied from the supplied lab file. It is not executed by this reference.

Cache-Poisoning/web/app.py · complete original Flask application
#!/usr/bin/env python3
"""
Vulnerable Flask Application - Redis Cache Poisoning Lab
This application demonstrates cache poisoning via unkeyed headers.
"""

import os
import redis
from flask import Flask, request, jsonify, make_response

app = Flask(__name__)

# Redis connection
REDIS_HOST = os.environ.get('REDIS_HOST', 'redis-db')
REDIS_PORT = int(os.environ.get('REDIS_PORT', 6379))
redis_client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, decode_responses=True)

# Cache configuration
CACHE_KEY = "index_page"  # VULNERABILITY: Static cache key - does not include X-Forwarded-Host
CACHE_TTL = 60  # Cache for 60 seconds

# Secret configuration for FLAG 2
# When user poisons cache with this exact host, FLAG 2 is revealed
SECRET_POISON_HOST = os.environ.get('SECRET_POISON_HOST', 'flag.securebank.internal')

def get_flag_two():
    """Read FLAG_TWO from file (set during Docker build)."""
    flag_path = '/opt/flag2.txt'
    try:
        if os.path.exists(flag_path):
            with open(flag_path, 'r') as f:
                return f.read().strip()
    except Exception:
        pass
    return "FLAG{n0t_s3t}"


def generate_secret_flag_html():
    """Generate the secret flag banner HTML."""
    flag_value = get_flag_two()
    return f'''
        <!-- SECRET FLAG UNLOCKED! You found the magic poison host! -->
        <div class="secret-flag" style="background: linear-gradient(90deg, #ff6b3522, #ff6b3511); border: 2px solid #ff6b35; border-radius: 10px; padding: 2rem; margin-top: 2rem; text-align: center;">
            <h3 style="color: #ff6b35;">CONGRATULATIONS! Cache Poisoning Successful!</h3>
            <p style="color: #ff6b35; font-family: monospace; font-size: 1.2rem; margin-top: 1rem;">
                <strong>FLAG 2:</strong> {flag_value}
            </p>
            <p style="color: #888; font-size: 0.9rem; margin-top: 0.5rem;">
                You successfully poisoned the cache with the secret host!
            </p>
        </div>
        '''


def generate_page_html(support_host, show_secret_flag=False):
    """Generate the main dashboard HTML with the support portal link."""
    secret_flag_html = generate_secret_flag_html() if show_secret_flag else ''
    
    return f'''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SecureBank Dashboard</title>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            min-height: 100vh;
            color: #eee;
        }}
        .navbar {{
            background: rgba(0,0,0,0.3);
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #333;
        }}
        .logo {{
            font-size: 1.5rem;
            font-weight: bold;
            color: #00d4ff;
        }}
        .nav-links a {{
            color: #aaa;
            text-decoration: none;
            margin-left: 2rem;
            transition: color 0.3s;
        }}
        .nav-links a:hover {{
            color: #00d4ff;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }}
        .hero {{
            text-align: center;
            padding: 4rem 0;
        }}
        .hero h1 {{
            font-size: 2.5rem;
            margin-bottom: 1rem;
        }}
        .hero p {{
            color: #888;
            font-size: 1.1rem;
        }}
        .cards {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 2rem;
            margin-top: 3rem;
        }}
        .card {{
            background: rgba(255,255,255,0.05);
            border-radius: 10px;
            padding: 2rem;
            border: 1px solid #333;
            transition: transform 0.3s, box-shadow 0.3s;
        }}
        .card:hover {{
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,212,255,0.2);
        }}
        .card h3 {{
            color: #00d4ff;
            margin-bottom: 1rem;
        }}
        .card p {{
            color: #888;
            line-height: 1.6;
        }}
        .support-banner {{
            background: linear-gradient(90deg, #00d4ff22, #00d4ff11);
            border: 1px solid #00d4ff44;
            border-radius: 10px;
            padding: 2rem;
            margin-top: 3rem;
            text-align: center;
        }}
        .support-banner a {{
            color: #00d4ff;
            font-weight: bold;
            text-decoration: none;
        }}
        .support-banner a:hover {{
            text-decoration: underline;
        }}
        .footer {{
            text-align: center;
            padding: 2rem;
            color: #555;
            margin-top: 4rem;
            border-top: 1px solid #333;
        }}
        .cache-info {{
            position: fixed;
            bottom: 10px;
            right: 10px;
            background: rgba(0,0,0,0.7);
            padding: 0.5rem 1rem;
            border-radius: 5px;
            font-size: 0.8rem;
            color: #666;
        }}
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="logo">🏦 SecureBank</div>
        <div class="nav-links">
            <a href="/">Dashboard</a>
            <a href="/status">Status</a>
            <a href="/accounts">Accounts</a>
            <a href="/transfers">Transfers</a>
        </div>
    </nav>

    <div class="container">
        <div class="hero">
            <h1>Welcome to SecureBank</h1>
            <p>Your trusted partner in digital banking solutions</p>
        </div>

        <div class="cards">
            <div class="card">
                <h3>💳 Account Overview</h3>
                <p>View your account balances, recent transactions, and manage your finances all in one place.</p>
            </div>
            <div class="card">
                <h3>💸 Quick Transfer</h3>
                <p>Send money instantly to friends, family, or businesses with our secure transfer system.</p>
            </div>
            <div class="card">
                <h3>📊 Analytics</h3>
                <p>Track your spending patterns and get insights to better manage your money.</p>
            </div>
        </div>

        <!-- VULNERABILITY: This link uses X-Forwarded-Host header which is not part of the cache key -->
        <div class="support-banner">
            <h3>Need Help?</h3>
            <p>Visit our <a href="http://{support_host}/support">Support Portal</a> for 24/7 assistance</p>
            <p style="color: #666; font-size: 0.9rem; margin-top: 0.5rem;">
                Or call us at 1-800-SECURE-BANK
            </p>
        </div>
        
        {secret_flag_html}
    </div>

    <div class="footer">
        <p>&copy; 2024 SecureBank. All rights reserved. | 
        <a href="/privacy" style="color: #555;">Privacy</a> | 
        <a href="/terms" style="color: #555;">Terms</a></p>
    </div>

    <div class="cache-info">
        Cached Response | TTL: {CACHE_TTL}s
    </div>
</body>
</html>'''


@app.route('/')
def index():
    """
    Main dashboard page.
    VULNERABILITY: Uses static cache key while the page content depends on X-Forwarded-Host header.
    This allows cache poisoning attacks.
    
    SECRET: If X-Forwarded-Host matches the secret poison host, FLAG 2 is revealed!
    """
    # Check if page is cached
    cached_page = redis_client.get(CACHE_KEY)
    
    if cached_page:
        # Return cached version (potentially poisoned!)
        response = make_response(cached_page)
        response.headers['X-Cache'] = 'HIT'
        return response
    
    # Get X-Forwarded-Host header (or use default)
    # VULNERABILITY: This header is used in content but NOT in cache key
    forwarded_host = request.headers.get('X-Forwarded-Host', 'support.securebank.local')
    
    # SECRET: Check if user discovered the magic poison host!
    show_secret_flag = (forwarded_host.lower() == SECRET_POISON_HOST.lower())
    
    # Generate page with the (potentially malicious) host
    page_html = generate_page_html(forwarded_host, show_secret_flag=show_secret_flag)
    
    # Cache the page with static key (VULNERABILITY!)
    redis_client.setex(CACHE_KEY, CACHE_TTL, page_html)
    
    response = make_response(page_html)
    response.headers['X-Cache'] = 'MISS'
    return response


@app.route('/status')
def status():
    """
    Status endpoint - displays build information including FLAG_ONE.
    """
    # Read flag from file (set during Docker build)
    flag_path = '/opt/flag1.txt'
    flag_value = "FLAG_NOT_SET"
    
    try:
        if os.path.exists(flag_path):
            with open(flag_path, 'r') as f:
                flag_value = f.read().strip()
    except Exception as e:
        flag_value = f"Error reading flag: {str(e)}"
    
    status_info = {
        "application": "SecureBank Dashboard",
        "version": "2.1.0",
        "status": "operational",
        "cache_backend": "Redis",
        "cache_ttl_seconds": CACHE_TTL,
        "build_id": flag_value,
        "environment": os.environ.get('FLASK_ENV', 'production'),
        "redis_connected": redis_client.ping() if redis_client else False
    }
    
    return jsonify(status_info)


@app.route('/admin/shell')
def admin_shell():
    """
    Hidden admin endpoint for Redis diagnostics.
    Requires 'Admin' cookie to be set with value 'true'.
    Allows running INFO command against Redis.
    """
    # Check for Admin cookie
    admin_cookie = request.cookies.get('Admin')
    
    if admin_cookie != 'true':
        return jsonify({
            "error": "Unauthorized",
            "message": "Admin access required"
        }), 403
    
    # Get command parameter (only INFO is allowed for "safety")
    cmd = request.args.get('cmd', 'INFO')
    
    # Whitelist of "safe" commands (but we'll be lenient for the lab)
    allowed_commands = ['INFO', 'PING', 'KEYS', 'GET', 'DBSIZE', 'TIME']
    
    try:
        if cmd.upper() == 'INFO':
            result = redis_client.info()
        elif cmd.upper() == 'PING':
            result = redis_client.ping()
        elif cmd.upper() == 'KEYS':
            pattern = request.args.get('pattern', '*')
            result = redis_client.keys(pattern)
        elif cmd.upper() == 'GET':
            key = request.args.get('key', '')
            if not key:
                return jsonify({"error": "Missing 'key' parameter"}), 400
            result = redis_client.get(key)
        elif cmd.upper() == 'DBSIZE':
            result = redis_client.dbsize()
        elif cmd.upper() == 'TIME':
            result = redis_client.time()
        else:
            return jsonify({
                "error": "Command not allowed",
                "allowed": allowed_commands
            }), 400
        
        return jsonify({
            "command": cmd,
            "result": result
        })
    
    except Exception as e:
        return jsonify({
            "error": str(e)
        }), 500


@app.route('/cache/clear')
def clear_cache():
    """Utility endpoint to clear the cache (for testing)."""
    try:
        redis_client.delete(CACHE_KEY)
        return jsonify({"message": "Cache cleared", "key": CACHE_KEY})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/robots.txt')
def robots():
    """Robots.txt that hints at hidden endpoints."""
    content = """User-agent: *
Disallow: /admin/
Disallow: /admin/shell
Disallow: /internal/
# Note: Admin endpoints require authentication cookie
"""
    response = make_response(content)
    response.headers['Content-Type'] = 'text/plain'
    return response


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)
Read Cache-Poisoning/docker-compose.yml · complete service and seed configuration · includes lab flag values

This is inert text copied from the supplied lab file. It is not executed by this reference. It contains values intended for this training lab.

Cache-Poisoning/docker-compose.yml · complete service and seed configuration · includes lab flag values
# Redis Cache Poisoning Pentesting Lab
# Docker Compose Configuration
#
# Services:
#   - web-app: Vulnerable Flask application with Redis caching
#   - redis-db: Redis backend with secret flag
#
# Usage:
#   docker compose build
#   docker compose up -d
#   Access Target App at http://localhost:5000

version: '3.8'

services:
  # =============================================================
  # WEB-APP: Vulnerable Flask Application
  # Contains cache poisoning vulnerability via X-Forwarded-Host
  # =============================================================
  web-app:
    build:
      context: ./web
      dockerfile: Dockerfile
      args:
        # FLAG_ONE is exposed via /status endpoint (reconnaissance)
        FLAG_ONE: "FLAG{r3c0n_1s_k3y_t0_succ3ss_4521}"
        # FLAG_TWO is revealed when cache is poisoned with secret host
        FLAG_TWO: "FLAG{p01s0n_th3_c4ch3_w1th_s3cr3t_h0st_7832}"
    container_name: web-app
    hostname: securebank
    ports:
      - "5000:5000"    # Flask application
    environment:
      - REDIS_HOST=redis-db
      - REDIS_PORT=6379
      - FLASK_ENV=production
      # The secret host that unlocks FLAG_TWO when used in cache poisoning
      - SECRET_POISON_HOST=flag.securebank.internal
    networks:
      lab-network:
        aliases:
          - securebank.local
          - www.securebank.local
    depends_on:
      redis-db:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5000/status')"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 10s
    restart: unless-stopped

  # =============================================================
  # REDIS-DB: Cache Backend
  # Contains hints about the secret poison host
  # =============================================================
  redis-db:
    image: redis:7-alpine
    container_name: redis-db
    hostname: redis
    ports:
      - "6379:6379"    # Redis port (exposed for debugging, remove in production)
    networks:
      - lab-network
    # Initialize Redis with secret hint data
    command: >
      sh -c "
        redis-server --appendonly yes &
        sleep 2 &&
        redis-cli SET 'config:cache:secret_host' 'flag.securebank.internal' &&
        redis-cli SET 'config:cache:description' 'Internal flag endpoint for cache validation' &&
        redis-cli SET 'internal:admin:password' 'SuperSecretAdminPass123!' &&
        redis-cli SET 'internal:api:key' 'sk-live-abcd1234efgh5678ijkl9012' &&
        wait
      "
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 5s
    volumes:
      - redis-data:/data
    restart: unless-stopped

# =============================================================
# Networks
# =============================================================
networks:
  lab-network:
    driver: bridge
    ipam:
      config:
        - subnet: 172.28.0.0/16

# =============================================================
# Volumes
# =============================================================
volumes:
  redis-data:
    driver: local
Read Cache-Poisoning/web/Dockerfile · complete web image build definition

This is inert text copied from the supplied lab file. It is not executed by this reference.

Cache-Poisoning/web/Dockerfile · complete web image build definition
# Web Application Dockerfile
# Vulnerable Flask app for Redis Cache Poisoning Lab

FROM python:3.11-slim-bookworm

# Build arguments for FLAGS
ARG FLAG_ONE="FLAG{default_flag_not_set}"
ARG FLAG_TWO="FLAG{default_flag2_not_set}"

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    FLASK_ENV=production \
    REDIS_HOST=redis-db \
    REDIS_PORT=6379

# Create app directory
WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY app.py .

# Write FLAGS to files
# FLAG_ONE: Exposed via /status endpoint (reconnaissance)
# FLAG_TWO: Revealed when cache is poisoned with secret host
RUN echo "${FLAG_ONE}" > /opt/flag1.txt && \
    echo "${FLAG_TWO}" > /opt/flag2.txt && \
    chmod 644 /opt/flag1.txt /opt/flag2.txt

# Create non-root user for security
RUN useradd --create-home --shell /bin/bash appuser && \
    chown -R appuser:appuser /app

# Switch to non-root user
USER appuser

# Expose port
EXPOSE 5000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/status')" || exit 1

# Run the application with gunicorn
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "--workers", "2", "--threads", "4", "app:app"]