Back to Attack Techniques

Command Injection

Explore the dangers, mechanisms, and defenses against Command Injection attacks.

What is Command Injection?

Command Injection is a security vulnerability that allows an attacker to execute arbitrary system commands on the host operating system via a vulnerable application.

Impact of Command Injection Attacks

  • Unauthorized access to sensitive data
  • System compromise
  • Data manipulation or destruction
  • Privilege escalation
  • Use of the compromised system for further attacks

Common Command Injection Attack Vectors

  • Unsanitized user input in system commands
  • Use of shell_exec, exec, system, or similar functions with user input
  • Improper handling of special characters in user input
  • Lack of input validation and sanitization
  • Use of outdated or vulnerable libraries and frameworks

Preventing Command Injection Attacks

  • Validate and sanitize all user inputs
  • Use parameterized queries or prepared statements
  • Implement the principle of least privilege
  • Use a whitelist of allowed characters and commands
  • Avoid using system commands with user input whenever possible
  • Implement proper error handling to avoid information disclosure
  • Use Web Application Firewalls (WAF) to filter malicious requests
  • Regularly update and patch all software and dependencies
  • Conduct regular security audits and penetration testing
  • Educate developers about secure coding practices and common command injection vulnerabilities

Command Injection Attack Simulation

Experience a simulated Command Injection attack

Command Injection Vulnerability Examples

Common code patterns that can lead to Command Injection vulnerabilities (for educational purposes only)

Basic Command Injection

If userInput is '8.8.8.8 && cat /etc/passwd', it will execute both commands.

ping userInput

Command Injection in PHP

If filename is 'secret.txt; rm -rf /', it will display the file content and then attempt to delete all files.

<?php system('cat ' . $_GET['filename']); ?>

Command Injection in Python

If user_input is '$(rm -rf /)', it will attempt to delete all files.

import os
os.system('echo ' + user_input)

Command Injection in Node.js

If userInput is '8.8.8.8 && cat /etc/passwd', it will execute both commands.

const { exec } = require('child_process');
exec('ping ' + userInput, (error, stdout, stderr) => {
  console.log(stdout);
});