从用户控制的源代码构建的系统命令¶
ID: swift/command-line-injection
Kind: path-problem
Security severity: 9.8
Severity: error
Precision: high
Tags:
- security
- external/cwe/cwe-078
- external/cwe/cwe-088
Query suites:
- swift-code-scanning.qls
- swift-security-extended.qls
- swift-security-and-quality.qls
使用未经清理的用户输入构建系统命令很危险,因为恶意用户可能会构造输入以执行任意代码。
建议¶
如果可能,使用硬编码的字符串字面量来指定要运行的命令。不要直接将用户输入解释为命令名称,而是检查输入,然后从硬编码的字符串字面量中选择。
如果不可能,则添加清理代码以验证用户输入在使用之前是否安全。
示例¶
以下示例在未经清理的情况下执行来自用户输入的代码
var task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", userControlledString] // BAD
task.launch()
如果用户输入用于构建命令,则应先进行检查。这确保了用户无法插入具有特殊含义的字符
func validateCommand(_ command: String) -> String? {
let allowedCommands = ["ls -l", "pwd", "echo"]
if allowedCommands.contains(command) {
return command
}
return nil
}
if let validatedString = validateCommand(userControlledString) {
var task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", validatedString] // GOOD
task.launch()
}