You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ProcessBuilder如何防范OS命令注入?为何推荐它而非Runtime.exec?

Why ProcessBuilder Is Preferred Over Runtime.exec for Preventing OS Command Injection

Great question—you’ve hit on a key difference that makes ProcessBuilder far safer for executing external commands with untrusted input. Let’s break this down clearly:

1. Yes, the Single String vs. Split Arguments Is the Core Reason

You’re exactly right: Runtime.getRuntime().exec(String command) treats the input as a single shell command string, which means it gets parsed by the underlying OS shell (like bash on Linux or cmd.exe on Windows). This shell parsing is where command injection risks creep in—malicious input can include shell metacharacters (like ;, &&, |, or $(...)) to execute unintended commands.

On the other hand, ProcessBuilder is designed to take the command and its arguments as separate elements in a list (or via command() calls that add individual parts). It never passes the input through a shell; instead, it directly launches the target executable with the arguments you specify as distinct, uninterpreted values.

2. How ProcessBuilder Prevents Command Injection

The magic lies in how ProcessBuilder interacts with the OS to create processes:

  • It bypasses the system shell entirely. When you use new ProcessBuilder("cat", userProvidedFilename).start(), the OS launches the cat executable and passes userProvidedFilename as a single, literal argument—no shell gets a chance to parse that argument as part of a command chain.
  • Malicious metacharacters in input become harmless. For example, if an attacker tries to pass file.txt; rm -rf / as the filename, ProcessBuilder will pass that entire string as a single argument to cat. Instead of executing rm, cat will just try to read a file named file.txt; rm -rf / (which almost certainly doesn’t exist, but no damage is done).

Example: Unsafe vs. Safe Usage

Unsafe (Runtime.exec with single string)

// Risky! If userInput is "file.txt; rm -rf /", this executes two commands
Runtime.getRuntime().exec("cat " + userInput);

Safe (ProcessBuilder with split arguments)

// Safe! Even if userInput has shell metacharacters, it's treated as a single filename
new ProcessBuilder("cat", userInput).start();

Important Caveat

While ProcessBuilder eliminates the shell-based injection risk, it doesn’t replace proper input validation. You should still validate and sanitize untrusted input (e.g., reject filenames with invalid characters for your filesystem) to avoid other issues like path traversal attacks. But it removes the biggest vector for OS command injection by design.

内容的提问来源于stack exchange,提问作者Venkatesh Laguduva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:19:49