security runtime_error ai_generated true

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

Command injection via file upload filename when processed by system shell

ID: security/command-injection-via-file-upload-filename

其他格式: JSON · Markdown 中文 · English
91%修复率
87%置信度
1证据数
2024-07-08首次发现

版本兼容性

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

根因分析

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

English

The application passes the uploaded file's filename directly to a system shell command (e.g., via exec, system, or subprocess) without sanitization, allowing an attacker to inject arbitrary commands using shell metacharacters like ;, |, or `.

generic

官方文档

https://owasp.org/www-community/attacks/Command_Injection

解决方案

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

无效尝试

常见但无效的做法:

  1. Use escapeshellarg() in PHP to escape the filename 30% 失败

    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.

  2. Remove only semicolons and pipes from the filename 50% 失败

    Attackers can use other metacharacters like backticks, $(), or newlines to execute commands. Partial sanitization is insufficient.

  3. Use a blacklist to block common command injection patterns 60% 失败

    Blacklists are easily bypassed with encoding, obfuscation, or using less common shell features. A whitelist is more secure.