Skip to main content
OS Command Injection & Insecure File Uploads
Lesson 9 of 18

OS Command Injection & Insecure File Uploads

Understand how shell metacharacters turn application parameters into OS commands, how attackers bypass naive file-upload filters, and how parameterized execution and safe upload pipelines prevent server compromise.

Intermediate 28 min Web security
Authorised environments only — The techniques described here are used only in training labs and on systems you own or have written permission to test.

Learning objectives

  • Explain why invoking a system shell with concatenated user input enables OS command injection
  • Identify in-band and blind command-injection signals safely in a controlled lab
  • Evaluate common file-upload filter bypasses including Content-Type spoofing, alternate extensions, and polyglots
  • Implement shell-free process APIs and layered file-upload validation outside the webroot

Recommended first: HTTP Request/Response, Cookies & Session ManagementIDOR, Path Traversal and Core Web AttacksSSRF Fundamentals & Local/Remote File Inclusion

#Why this matters

Web applications often rely on the host operating system to run diagnostic utilities (ping, nslookup), convert media (ffmpeg, ImageMagick), or accept user files (profile photos, invoices, archives). Both patterns bridge HTTP traffic directly to the server's filesystem and process table.

When user input is concatenated into a shell string, a single separator character lets an attacker run arbitrary OS commands under the web service account. When uploaded files are stored with user-supplied names inside an executable web directory, an attacker can upload a script and trigger it over HTTP.

#How OS command injection works

Command injection occurs when an application launches a shell (/bin/sh -c on Linux or cmd.exe /c on Windows) with a single string built from untrusted input:

python
import subprocess

# Vulnerable: shell=True passes the whole string to /bin/sh -c
host = request.args.get("host", "127.0.0.1")
output = subprocess.check_output(f"ping -c 1 {host}", shell=True, text=True)

If host is 127.0.0.1; id, the shell executes ping -c 1 127.0.0.1 and then executes id. Even when command output is hidden (blind injection), time delays or out-of-band DNS/HTTP lookups reveal execution:

Probing in-band and blind command injection in a lab
$ curl -s "http://lab.local/diag?host=127.0.0.1%3B%20echo%20LAB_OK"
1 packets transmitted, 1 received
LAB_OK
$ curl -s -o /dev/null -w "time=%{time_total}s\n" "http://lab.local/diag?host=127.0.0.1%20%26%26%20sleep%205"
time=5.124s

Common shell metacharacters work differently depending on whether the previous command succeeds:

Operator / syntax Behaviour in /bin/sh Useful when
; Runs second command unconditionally In-band or blind testing after a valid argument
&& Runs second command only if first exits 0 First command must succeed
|| Runs second command only if first fails Injecting after an invalid argument
$(cmd) or `cmd` Command substitution inside an argument Input sits inside double quotes
%0a (newline) Starts a new command line Semicolons and ampersands are filtered

#Insecure file uploads and common bypasses

File upload features fail when developers trust metadata supplied by the client or leave uploaded files in a directory where the web server executes scripts.

Upload filter bypass via Content-Type spoofingUpload filter bypass via Content-Type spoofingBrowserlab.localPOST /upload (filename="check.php", Content-Type: image/png)200 OK (saved at /uploads/check.php)GET /uploads/check.php200 OK (script output returned)

In a lab audit, testers check each layer of upload validation:

Weak defence Why it fails Safe verification check
Client-side JS check Runs only in the browser Intercept the multipart request in Burp Suite and change the filename
Content-Type header check Completely controlled by the sender Upload a .php or .svg file while sending Content-Type: image/jpeg
Extension blocklist (.php) Misses variants and other dangerous types Test .phtml, .phar, uppercase .PhP, or .svg (for stored XSS)
Original filename preserved Allows path traversal or .htaccess overwrite Test ../ in filename or uploading config files in Apache labs
Magic-byte prefix check only Ignores trailing script code Prepend GIF89a; before a harmless <?php echo "OK"; ?> marker

Even when server-side code execution is blocked, allowing inline .svg or .html uploads from the main application origin gives an attacker stored Cross-Site Scripting (XSS) as soon as a victim visits the uploaded file URL.

#Defending command execution and uploads

Preventing OS command injection:

  1. Avoid spawning external commands. Use native language libraries (ipaddress, Pillow, zipfile) instead of ping, convert, or unzip.
  2. Use parameterized process APIs with shell=False. Pass the executable and each argument as a separate list element so metacharacters are never interpreted by a shell:
python
import ipaddress
import subprocess

# Safe: validate input format and invoke ping directly without a shell
addr = str(ipaddress.ip_address(user_host))
result = subprocess.run(["ping", "-c", "1", addr], shell=False, capture_output=True, text=True, check=False)
  1. Apply strict allow-lists. Validate characters (such as valid IPv4/IPv6 addresses or [a-zA-Z0-9.-]+ hostnames) before passing values to any binary.

Securing file uploads:

  • Enforce a strict extension allow-list (for example .png, .jpg, .pdf) on the server after stripping any directory components (basename).
  • Rename every saved file to a server-generated random UUID and store it outside the webroot or in dedicated object storage.
  • Verify file contents with magic-byte checks and, for images, decode and re-encode the image to strip embedded comments or polyglot code.
  • Serve user files from a separate domain or with Content-Disposition: attachment and X-Content-Type-Options: nosniff so browsers never render .svg or .html inline.

#Common mistakes

  • Filtering ; and | while overlooking $(...), backticks, or URL-encoded newlines (%0a).
  • Passing shell=True in Python subprocess or exec() in Node.js while assuming input validation alone is enough.
  • Relying on the multipart Content-Type header or client-side <input accept="..."> attributes as security controls.
  • Using an extension blocklist instead of an allow-list, or keeping user-supplied filenames when saving files to disk.

#Summary

  • OS command injection happens when untrusted data enters a shell command string, allowing metacharacters to run extra commands.
  • Prevent command injection by using native libraries or argument-array APIs with shell=False, paired with strict input allow-lists.
  • Insecure file uploads arise from trusting client Content-Type headers, incomplete extension blocklists, or storing user files in executable web directories.
  • Secure uploads with server-side extension allow-lists, content re-encoding, random UUID filenames outside the webroot, and Content-Disposition: attachment plus nosniff.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge