Ci

1. Python - Command Injection via Sub process
import subprocess
command = input("Enter the command to run: ")
subprocess.call(command, shell=True)
- Explanation: The
shell=True
argument makes this code vulnerable to command injection. If an attacker enters a command like ls; whoami
, it will execute both ls
and whoami
.
2. PHP - Command Injection in System Functions
<?php
$file = $_GET['file'];
system("cat " . $file);
?>
- Explanation: This PHP code is vulnerable because user input is directly appended to a system command. An attacker can manipulate the
file
parameter, e.g., file=/etc/passwd;ls
, to read sensitive files and execute additional commands.
3. Java - Command Injection with Runtime.exec()
import java.io.*;
public class CommandInjection {
public static void main(String[] args) throws IOException {
String userInput = args[0];
Runtime.getRuntime().exec("ping " + userInput);
}
}
- Explanation: The
Runtime.getRuntime().exec()
method is dangerous when used with untrusted input. An attacker could input something like 127.0.0.1 && echo hacked
, leading to the execution of both commands.
4. Bash - Command Injection via Variable Substitution
#!/bin/bash
echo "Enter your name:"
read name
eval "echo Hello, $name"
- Explanation: The
eval
command evaluates the input as a Bash command. If the user inputs John; rm -rf /
, the script will execute the malicious rm
command, which could lead to catastrophic consequences.
5. Node.js - Command Injection with child_process.exec
const { exec } = require('child_process');
const userInput = process.argv[2];
exec(`ls ${userInput}`, (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
console.log(`Output: ${stdout}`);
});
- Explanation: The
exec
function runs the command in a shell, making it vulnerable to injection. An attacker can pass && whoami
as input to execute additional commands.
6. C - Command Injection in System Calls