# 通过文件上传文件名在系统 shell 处理时导致命令注入

- **ID:** `security/command-injection-via-file-upload-filename`
- **领域:** security
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 91%

## 根因

应用程序将上传文件的文件名直接传递给系统 shell 命令（例如通过 exec、system 或 subprocess），而未进行清理，允许攻击者使用 shell 元字符（如 ;、| 或 `）注入任意命令。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| PHP 8.3.0 | active | — | — |
| Node.js 20.11.0 | active | — | — |
| Python 3.12.0 | active | — | — |
| Apache Commons IO 2.15.0 | active | — | — |

## 解决方案

1. ```
   完全避免使用用户输入的系统 shell 命令。使用语言原生 API 进行文件操作。例如，在 Node.js 中，使用 `fs.rename(uploadedFile.path, '/target/' + sanitizedFilename)` 而不是 `exec('mv ' + filename + ' /target/')`。通过移除除点和连字符之外的所有非字母数字字符来清理文件名：`filename.replace(/[^a-zA-Z0-9._-]/g, '')`。
   ```
2. ```
   如果无法避免 shell 命令，则对文件名使用白名单允许的字符，并拒绝任何不匹配的输入。例如，在 Python 中：`import re; if not re.match(r'^[a-zA-Z0-9._-]+$', filename): raise ValueError('Invalid filename')`。然后使用 `subprocess.run(['mv', filename, '/target/'], shell=False)` 避免 shell 解释。
   ```
3. ```
   使用专用库进行安全命令执行，例如 Java 中的 Apache Commons Exec，它提供避免 shell 注入的 `CommandLine` 和 `Executor` 类。示例：`CommandLine cmdLine = new CommandLine("mv"); cmdLine.addArgument(filename); cmdLine.addArgument("/target/"); DefaultExecutor executor = new DefaultExecutor(); executor.execute(cmdLine);`。
   ```

## 无效尝试

- **Use escapeshellarg() in PHP to escape the filename** — escapeshellarg() escapes the argument for the shell, but if the command is constructed incorrectly (e.g., using double quotes), it may still be vulnerable. Also, it does not prevent injection if the filename is used in a context like `mv $filename /target/` without quotes. (30% 失败率)
- **Remove only semicolons and pipes from the filename** — Attackers can use other metacharacters like backticks, $(), or newlines to execute commands. Partial sanitization is insufficient. (50% 失败率)
- **Use a blacklist to block common command injection patterns** — Blacklists are easily bypassed with encoding, obfuscation, or using less common shell features. A whitelist is more secure. (60% 失败率)
