コンテンツにスキップ

Command Injection

コマンドインジェクション

説明

コマンドインジェクションは、サーバーのオペレーティングシステム内でのコマンドの不正な実行を許可するセキュリティ侵害です。これは、アプリケーションが検証されていないユーザー入力(フォーム、Cookie、HTTPヘッダーなどから)を誤ってシステムシェルに直接転送した場合に発生します。これにより、攻撃者は通常、脆弱なアプリケーションと同じ権限で独自のコマンドを実行できます。コマンドインジェクション攻撃は、主に入力検証が不十分なために可能になります。

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);

推奨事項

コマンドインジェクションの脆弱性を軽減するには、以下の推奨事項があります。

  • ユーザー提供入力の実行の回避: コマンドやシステムシェル内で、ユーザー提供データを直接実行することは控えてください。可能な限り、ホワイトリストや事前定義されたオプションを検証して使用してください。

  • 連結の回避: ユーザー入力をシステムコマンドに直接連結することは避け、代わりに引数の個別のリストで渡します。

  • 入力の検証とサニタイズ: ユーザー入力は常に検証し、サニタイズしてください。システムシェルまたはコマンド実行関数に渡されるユーザー提供データは、サニタイズされ、期待される文字またはパターンに制限されていることを確認します。

  • 最小特権の原則: 必要なアクションを実行するために最低限必要な権限で、アプリケーションまたはサービスを実行します。スーパーユーザーまたは管理者の権限でサービスを実行することは避けてください。

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