Hostname regular expression validation bypass in Swift

Hostname regular expression validation bypass in Swift

Description

Searching a whole URL for an allowed hostname can match text outside the actual destination. Validate the complete hostname, including its dot separators.

Potential impact

A redirect or server request that relies on a partial match can reach an unapproved domain.

Remediation

Parse the URL with URLComponents. Match the scheme and hostname exactly, reject usernames and passwords, and allow only an omitted port or an approved port. If you use a regular expression on the hostname, anchor both ends and escape dots as \..

Examples

Before

swift
let regex = try Regex(#"https?://www\.example\.com"#)

After

swift
import Foundation

func isAllowedURL(_ value: String) -> Bool {
    guard let components = URLComponents(string: value),
          components.scheme?.lowercased() == "https",
          components.host?.lowercased() == "www.example.com",
          components.user == nil,
          components.password == nil,
          components.port == nil || components.port == 443 else {
        return false
    }
    return true
}

The function permits only HTTPS URLs for www.example.com. It rejects user information and any explicit port other than 443.

References