Swift User Input In Regular Expression
Description
Identifies Swift code where user input is used to construct regular expression patterns. This is dangerous because malicious input could create regex patterns that cause catastrophic backtracking, leading to Regular Expression Denial of Service (ReDoS) attacks.
Detection Strategy
• Look for Swift code using the 'Regex' expression type
• Check if any arguments/parameters used to construct the Regex pattern come from user-controlled input sources
• Report a vulnerability if user input flows into Regex pattern construction without proper validation or sanitization
Vulnerable code example
import Foundation
func vulnerableRegex(userInput: String) {
// VULNERABLE: Directly using unsanitized user input in Regex constructor
let regex = try! Regex(userInput)
// VULNERABLE: Concatenating user input into regex pattern
let pattern = "^(" + userInput + ")$"...✅ Secure code example
import Foundation
func safeRegex(userInput: String) throws {
// Safe: Escape special regex characters in user input
let escapedInput = NSRegularExpression.escapedPattern(for: userInput)
// Safe: Use escaped input in regex pattern
let regex = try NSRegularExpression(pattern: escapedInput)...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.