
OSコマンドインジェクション
概要
深刻度:🔴 最高
IPA分類:1.2 OSコマンド・インジェクション
OWASP 2025:A05:2025 - Injection(5位)
OWASP 2021:A03:2021 - Injection(3位)
CWE:CWE-78
出典:https://www.ipa.go.jp/security/vuln/websecurity/os-command.html
内容
シェルを起動できる関数(system(), exec(), open() 等)を使う実装で、外部からの入力値がOSコマンドとして実行されてしまう問題。
発生しうる脅威
サーバ内ファイルの閲覧・改ざん・削除、重要情報の漏えい
意図しないOSシャットダウン、ユーザアカウントの追加・変更
ウイルス・ワーム感染、バックドアの設置
他システムへの攻撃の踏み台、迷惑メール送信
対策
根本的解決
シェルを起動できる言語機能の利用を避け、別の関数・APIで代替する
OSコマンド呼び出し自体が不要か見直す(ファイル操作・メール送信等は標準ライブラリで代替可能なことが多い)
保険的対策
シェル起動が避けられない場合、引数に対してホワイトリスト方式で入力チェックを行う
許可する文字の組み合わせを事前に定義し、それ以外は処理を中止する
ブラックリスト方式はチェック漏れが生じやすく非推奨
言語別実装ガイド
基本原則
「シェルを起動する」とは、コマンドを 文字列1つ としてシェル(/bin/sh, cmd.exe 等)に渡すこと。シェルが ; | && $() などのメタ文字を解釈するため、攻撃者がコマンドを追加・連結できてしまう。
「安全な代替」が安全な理由は、コマンド名と引数を 別々の値(配列・リスト) として OS に直接渡すため、シェルが介在せずメタ文字が文字として扱われるから。
# 危険(シェルがメタ文字を解釈する)
exec("convert " + userInput)
→ "convert img.png; rm -rf /" のように追加コマンドが実行される
# 安全(シェルを経由しない)
spawn("convert", ["img.png", userInput])
→ convert に "img.png" と userInput がそのまま引数として渡されるだけ
TypeScript / Node.js
危険な関数・オプション
child_process.exec(string):デフォルトで /bin/sh -c を起動しシェルにコマンド文字列を渡す
child_process.execSync(string):同上の同期版
spawn(cmd, { shell: true }):shell: true を指定するとシェル経由になる
spawnSync(cmd, { shell: true }):同上の同期版
安全な関数・オプション
spawn(cmd, [arg1, arg2]):shell オプションを省略(デフォルト false)すると直接バイナリを起動
execFile(cmd, [arg1, arg2]):シェルを起動せず指定ファイルを直接実行する
import { exec, spawn, execFile } from "child_process";
// 危険:exec に外部入力を渡す
exec(`convert ${userInput}`); // userInput = "img.png; rm -rf /" で破綻
// 安全:spawn でコマンドと引数を分離
const proc = spawn("convert", ["img.png", userInput]);
// または
execFile("convert", ["img.png", userInput], (err, stdout) => {
if (err) throw err;
console.log(stdout);
});
Python
危険な関数・オプション
os.system(string):シェル経由でコマンド文字列を実行する
os.popen(string):同上、パイプ付きで実行
subprocess.run(string, shell=True):shell=True でシェル経由になる
subprocess.call(string, shell=True):同上
subprocess.Popen(string, shell=True):同上
安全な関数・オプション
subprocess.run([cmd, arg1, arg2]):shell=False(デフォルト)でリスト渡しにするとシェルを経由しない
import subprocess, os
# 危険:shell=True + 文字列連結
os.system("convert " + user_input)
subprocess.run("convert " + user_input, shell=True)
# 安全:リスト形式で渡す(shell=False がデフォルト)
subprocess.run(["convert", "img.png", user_input])
# やむを得ず shell=True を使う場合はホワイトリストで検証済みの値のみ渡す
ALLOWED_COMMANDS = {"ping", "nslookup"}
if command not in ALLOWED_COMMANDS:
raise ValueError("Invalid command")
# ホワイトリスト検証後でも shell=False + リスト形式が推奨
subprocess.run([command, target])
Java
※noteではRuntimeのあとにgetRuntimeやexecを続けて書くと記事が保存できないのでスペースを入れています。
危険な関数・オプション
Runtime. getRuntime(). exec(String):単一文字列を渡すとシェルが起動する場合がある
new ProcessBuilder(String) に文字列連結:コマンドを文字列結合で組み立てると安全でない
安全な関数・オプション
Runtime. getRuntime(). exec(String[]):コマンドと引数を配列で分離して渡す
new ProcessBuilder(List<String>):リスト形式で分離して渡す。パス・環境変数制御も可能
// 危険:文字列連結で渡す
Runtime. getRuntime(). exec("convert " + userInput);
// 安全:配列で分離
String[] cmd = {"convert", "img.png", userInput};
Runtime. getRuntime(). exec(cmd);
// 推奨:ProcessBuilder でリスト形式
ProcessBuilder pb = new ProcessBuilder(
List.of("convert", "img.png", userInput)
);
pb.redirectErrorStream(true);
Process p = pb.start();Runtime. exec(String) は内部で StringTokenizer によりスペース区切りに分割するだけで、Unix 系ではシェルを起動しません。ただし、この分割方式ではパイプや環境変数展開が使えず、挙動が直感に反しやすいため、コマンドと引数を明示的に分離できる配列形式を使うことが推奨されます。
Go
危険な関数・オプション
exec.Command("sh", "-c", userInput):sh -c の引数に外部入力を渡すとシェルが解釈する
exec.Command("bash", "-c", userInput):同上
安全な関数・オプション
exec.Command(cmd, arg1, arg2):os/exec はデフォルトでシェルを経由しない。引数を分離して渡せば安全
import "os/exec"
// 危険:sh -c に外部入力を渡す
cmd := exec.Command("sh", "-c", "convert "+userInput)
// 安全:コマンドと引数を分離
cmd := exec.Command("convert", "img.png", userInput)
out, err := cmd.Output()
Go の強み: os/exec パッケージはデフォルトでシェルを使わない設計になっており、意図的に sh -c を使わない限りシェルインジェクションは発生しにくい。他言語と比べて安全な設計。
言語別まとめ
TypeScript
危険なパターン:exec("cmd " + input)
安全なパターン:spawn("cmd", [input])
Python
危険なパターン:subprocess.run("cmd " + input, shell=True)
安全なパターン:subprocess.run(["cmd", input])
Java
危険なパターン:Runtime. exec("cmd " + input)
安全なパターン:new ProcessBuilder(List.of("cmd", input))
Go
危険なパターン:exec.Command("sh", "-c", "cmd "+input)
安全なパターン:exec.Command("cmd", input)
共通の原則:コマンドと引数を分離し、文字列を連結してシェルに渡さない。