正则表达式注入¶
ID: swift/regex-injection
Kind: path-problem
Security severity: 7.5
Severity: error
Precision: high
Tags:
- security
- external/cwe/cwe-730
- external/cwe/cwe-400
Query suites:
- swift-code-scanning.qls
- swift-security-extended.qls
- swift-security-and-quality.qls
使用未经清理的用户输入构建正则表达式很危险,因为恶意用户可能会修改表达式的含义。他们可能能够导致意外的程序行为,或执行拒绝服务攻击。例如,他们可能会提供一个在最坏情况下需要指数时间评估的正则表达式片段。
建议¶
在将用户输入嵌入到正则表达式之前,请使用清理函数(例如 NSRegularExpression::escapedPattern(for:)
)来转义具有特殊含义的元字符。
示例¶
以下示例从用户输入构建正则表达式,但没有首先对其进行清理
func processRemoteInput(remoteInput: String) {
...
// BAD: Unsanitized user input is used to construct a regular expression
let regex1 = try Regex(remoteInput)
// BAD: Unsanitized user input is used to construct a regular expression
let regexStr = "abc|\(remoteInput)"
let regex2 = try NSRegularExpression(pattern: regexStr)
...
}
如果使用用户输入构建正则表达式,则应首先对其进行清理。这将确保用户无法插入在正则表达式中具有特殊含义的字符。
func processRemoteInput(remoteInput: String) {
...
// GOOD: Regular expression is not derived from user input
let regex1 = try Regex(myRegex)
// GOOD: User input is sanitized before being used to construct a regular expression
let escapedInput = NSRegularExpression.escapedPattern(for: remoteInput)
let regexStr = "abc|\(escapedInput)"
let regex2 = try NSRegularExpression(pattern: regexStr)
...
}
参考资料¶
OWASP:正则表达式拒绝服务 - ReDoS.
维基百科:ReDoS.
常见弱点枚举:CWE-730.
常见弱点枚举:CWE-400.