Description
Using user input directly as a regular expression pattern lets an attacker supply expensive or unexpected expressions, potentially causing denial of service or bypassing validation.
Potential impact
- Denial of service from slow regular expression processing
- Input validation bypass
- Exceptions or interrupted functionality
Remediation
- Escape user input with
NSRegularExpression.escapedPattern(for:)before including it in a pattern. - Keep the pattern structure static and select dynamic conditions from an allow-list.
- Apply input-length and execution-time limits when processing complex patterns.
Examples
Before
swift
import Foundation
import UIKit
func buildRegex(inputField: UITextField) throws {
let input = inputField.text ?? ""
let regex = try NSRegularExpression(pattern: input)
}
After
swift
import Foundation
import UIKit
func buildRegex(inputField: UITextField) throws {
let input = inputField.text ?? ""
let escaped = NSRegularExpression.escapedPattern(for: input)
let regex = try NSRegularExpression(pattern: escaped)
}
Explanation:
- Before: Input is interpreted as regular expression syntax.
- After: Escaping makes the input literal text.
Apply additional requirements, such as matching the entire string, according to the purpose of the call.