#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:
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:
$ 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.124sCommon 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.
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:
- Avoid spawning external commands. Use native language libraries (
ipaddress,Pillow,zipfile) instead ofping,convert, orunzip. - 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:
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)- 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: attachmentandX-Content-Type-Options: nosniffso browsers never render.svgor.htmlinline.
#Common mistakes
- Filtering
;and|while overlooking$(...), backticks, or URL-encoded newlines (%0a). - Passing
shell=Truein Pythonsubprocessorexec()in Node.js while assuming input validation alone is enough. - Relying on the multipart
Content-Typeheader 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-Typeheaders, 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: attachmentplusnosniff.