跳转至

Command Injection

命令注入

描述

命令注入是一种安全漏洞,它允许在服务器的操作系统中未经授权执行命令。当应用程序无意中将未经核实的用户输入(来自表单、Cookie、HTTP 标头等)直接传输到系统 Shell 时,就会发生这种情况。这使攻击者能够执行自己的命令,通常具有与受漏洞影响的应用程序相同的权限。命令注入攻击主要由于输入验证不足而成为可能。

示例

Java

String userInput = request.getParameter("input");
Runtime.getRuntime().exec("ls " + userInput);

Javascript

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

PHP

$userInput = $_GET['input'];
system('ls ' . $userInput);

建议

为了缓解命令注入漏洞,以下是一些建议:

  • 避免执行用户提供的输入:避免在命令或系统 Shell 中直接执行用户提供的数据。尽可能验证并使用白名单或预定义选项。

  • 避免拼接:避免将用户输入直接拼接到系统命令中,而应将其在单独的参数列表中传递。

  • 输入验证和清理:始终验证和清理用户输入。确保将任何传递给系统 Shell 或命令执行函数的用户提供的数据都进行清理,并限制为预期的字符或模式。

  • 最小权限原则:以执行必要操作所需的最低权限运行应用程序或服务。避免以超级用户或管理员权限运行服务。

示例

Java

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the file name: ");
String userInput = scanner.nextLine(); // Takes user input

// Sanitize user input to prevent command injection
String sanitizedInput = userInput.replaceAll("[^A-Za-z0-9]", ""); // Example sanitization

// Command execution
ProcessBuilder processBuilder = new ProcessBuilder("ls", "-l", sanitizedInput);

// Redirect error stream to output
processBuilder.redirectErrorStream(true);

Process process = processBuilder.start();

PHP

<?php
// User-supplied filename
$userInput = $_POST['filename']; // Example: 'file.txt'

// Validate and sanitize user input
if (preg_match('/^[a-zA-Z0-9_\.]+$/', $userInput)) { // Validate against alphanumeric and dot
    // Safely escape the user input to prevent command injection
    $escapedInput = escapeshellarg($userInput);

    // Command execution using the sanitized input
    $command = "ls -l " . $escapedInput;
    $output = shell_exec($command);

    echo "<pre>$output</pre>";
} else {
    echo "Invalid filename input!";
}
?>

链接

标准

  • CWE_TOP_25:
    • CWE_20
    • CWE_78
  • GDPR:
    • ART_5
    • ART_32
  • PCI_STANDARDS:
    • REQ_6_2
    • REQ_6_3
    • REQ_11_3
  • SOC2_CONTROLS:
    • CC_2_1
    • CC_3_4
    • CC_4_1
    • CC_7_1
    • CC_7_2
    • CC_7_4
    • CC_7_5
  • HIPAA_CONTROLS:
    • SECURITY212
    • SECURITY213
    • SECURITY255