logo

Database

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.

Weakness:

211 - Asymmetric denial of service - ReDoS

Category: Functionality Abuse

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)...