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.
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.
Request?file=…Caller controls the filename
Single-pass filterstr_replace('../', '', …)Newly formed text is not scanned again
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.
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
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:
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.
Stage
Value or behavior
What 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
Read
file_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.
Stage
Source behavior
Security question
Query parsing
Reads the URL-decoded $_GET['file'] and trims edge whitespace.
Percent-encoded ../ reaches the same filter as literal ../.
Filtering
Removes NUL bytes and existing matches in one pass per listed pattern.
Deletion can create a new forward-slash sequence that is not revisited.
Path construction
Concatenates the result to /var/www/html/files/.
No canonical containment check follows.
Access checks
Uses file_exists() and is_readable().
Existence and permissions are not directory containment.
File read
Loads bytes with file_get_contents().
PHP source is read as data; there is no requested-file include.
Response rendering
Escapes 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 wire
Source-level consequence
../config.inc.php
The existing ../ is removed; the viewer looks inside files/.
%2e%2e%2fconfig.inc.php
Decodes to the same direct traversal string and is filtered the same way.
%252e%252e%252fconfig.inc.php
One query decode leaves literal %2e%2e%2f; neither this handler nor the local filesystem decodes it again.
/etc/passwd
Becomes /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
Target
Evidence in supplied files
Impact described by the lab
policy.txt, report.txt, memo.txt
Present in the configured document folder
Normal viewer use and clues about the application.
robots.txt
Disallows /config.inc.php, among other paths
Hints that a config file exists; this is not access control.
config.inc.php
Outside files/, one level above it
Contains database, LDAP, and API configuration values in this lab.
viewer.php
Application source in the web root
Shows the exact path filter and file-read logic.
/var/flag.txt
Declared by the Dockerfile outside the web root
Training flag used to confirm the traversal.
/etc/passwd
System file in the container filesystem
Example 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
Question
Source-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.
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
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.
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.
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.
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 category
Expected source-level observation
Conclusion supported
Known document name
Path stays within the configured folder and content is displayed.
Normal viewer behavior and output-encoding path.
Direct ../ sequence
The 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 ....// sequence
One replacement leaves a new ../ in the filtered value.
The string-replacement bypass mechanism.
Known readable path outside the folder
If the resolved target exists and is readable, the viewer reads its bytes.
Arbitrary readable-file disclosure within the container's access boundary.
PHP source target
The 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
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.
Intended objectives, bypass explanation, expected flag, and mitigations.
Source reading map
Source area
What it answers
src/config.inc.php
Where is the document root configured, and which values does the application include?
src/viewer.php: request and filter logic
How is $_GET['file'] normalized, which strings are removed, and how is the target assembled?
src/viewer.php: read and render logic
Which filesystem checks run, which function reads bytes, and where is HTML escaping applied?
src/index.php and src/robots.txt
Which documents and route names are discoverable from the interface and crawler hints?
Dockerfile and docker-compose.yml
What image paths, permissions, service port, and host mapping are declared?
README and lab guides
Which 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
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