Skip to content

[NEW QUERY] Swift CWE-20: unvalidated custom URL scheme parameters and unchecked substring ranges - #350

Draft
felickz with Copilot wants to merge 4 commits into
mainfrom
copilot/swiftquery-createcwe-20
Draft

felickz with Copilot wants to merge 4 commits into
mainfrom
copilot/swiftquery-createcwe-20

Conversation

Copilot AI commented Oct 31, 2026 •

Copy link
Copy Markdown

AI Scan found two CWE-20 issues in iGoat-Swift that CodeQL default setup misses. The first is deep-link query parameters driving an alert. The second is NSString.range(of:) results used to slice a server response without checking that the delimiter was found. swift-all already treats the application(_:open:options:) URL as untrusted input, but no Swift query flags it reaching UI or actions, and nothing covers unchecked range lookups. This PR adds two queries under a new languages/swift/custom pack.

📝 Query Information

  • Language: swift
  • Query ID: swift/unvalidated-url-scheme-parameter, swift/unchecked-substring-range
  • Category: security
  • Severity: warning (security-severity 5.3, precision medium; targets Community Packs)
  • CWE/CVE (if applicable): CWE-20 (also CWE-939 for the URL-scheme query and CWE-129 for the substring query)

🎯 Description

What This Query Detects

swift/unvalidated-url-scheme-parameter (path-problem)

  • Sources: the URL argument of the custom-URL-scheme handlers:
    • UIApplicationDelegate: application(_:open:options:), application(_:handleOpen:), application(_:open:sourceApplication:annotation:)
    • UISceneDelegate: scene(_:openURLContexts:), plus the options parameter of scene(_:willConnectTo:options:)
  • Sinks:
    • UIAlertController(title:message:preferredStyle:) title and message
    • MFMessageComposeViewController recipients, body and subject
    • MFMailComposeViewController: setToRecipients, setCcRecipients, setBccRecipients, setSubject, setMessageBody
    • UIApplication.open / openURL
  • Extra flow steps: URLComponents init, members of URLComponents / URLQueryItem, and for x in <tainted collection>.
  • Barrier: a read of variable v is treated as safe only on the branch where v passed a check in an if/guard/while condition. Accepted checks are a Bool-returning call that takes v as an argument or receiver, or v == / != / ~= something. Checking only url.scheme does not count, so the iGoat case is still reported.

swift/unchecked-substring-range (problem)

  • Alerts on a call to NSString.range(of:…) when its result (or its .location / .length) flows into:
    • substring(with:), substring(from:), substring(to:), or replacingCharacters(in:with:)
    • NSRange(location:length:) or NSMakeRange
  • The call is suppressed if its result appears in any comparison in the same function, such as != NSNotFound or length == 0.

Example Vulnerable Code

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  if url.scheme == "igoat", let q = url.parametersInfo {
    let msg = q["message"] ?? ""
    UIAlertController.showAlertWith(title: "iGoat", message: "Message \(msg)")   // flagged
  }
  return true
}

let from = ns.range(of: "<td>key</td><td>")                                       // flagged
return ns.substring(with: NSRange(location: from.location + from.length, length: 8))

Example Safe Code

guard isValidPhoneNumber(number) else { return false }
if !allowedMessages.contains(text) { return false }
composer.recipients = [number]
composer.body = text

let r = ns.range(of: "=")
guard r.location != NSNotFound else { return nil }
return ns.substring(from: r.location + r.length)

🧪 Testing

  • Positive test cases included
  • Negative test cases included
  • Edge cases covered: the value is used in the failed-validation branch; the URL is used directly after guard let URLComponents(url:); a != check only applies on its false branch; only some parameters are validated; scene delegates; nested optional ranges
  • All tests pass

Tests use inline expectations (// $ Alert / // $ Source). They declare minimal stand-ins for the UIKit/Foundation types, so they extract without the Apple SDKs. The bundled 2.27.2 Swift extractor only works on macOS, so I extracted the test databases with CodeQL 2.17.6's Linux extractor and upgraded them with 2.27.2. On macOS, the path-step lines (edges / nodes) in UnvalidatedUrlSchemeParameter.expected may need re-accepting; the alerts themselves should not change.

📋 Checklist

  • Query compiles without errors
  • Documentation complete (.md and .qhelp): .md query help only, no .qhelp
  • Metadata properly set (@name, @id, @kind, etc.)
  • Tests validate query behavior
  • No false positives in test cases

🔗 References


Note: This query was developed using Test-Driven Development methodology.

Copilot AI and others added 2 commits October 31, 2026 05:05
…ked substring range

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
…quire Bool-valued checks

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Copilot AI changed the title [WIP] Add new query for CWE-20 in Swift [NEW QUERY] Swift CWE-20: unvalidated custom URL scheme parameters and unchecked substring ranges Oct 31, 2026
Copilot AI requested a review from felickz October 31, 2026 05:10
@felickz
felickz requested a balanced review from Copilot November 2, 2026 18:39

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Validation barriers can suppress alerts for reassigned URL values and unchecked substring ranges, while replacement text is incorrectly treated as a range bound, causing both missed findings and false positives.

3 open issues
What changed in this PR

Adds a custom Swift CodeQL pack addressing the detection gaps described in #300: unvalidated deep-link parameters and unchecked NSString search ranges.

Changes:

  • Adds two CWE-20 queries covering deep-link data reaching UI/actions and search results used as substring bounds.
  • Includes Swift fixtures, inline expectations, and expected query results.
  • Adds query help and source/test pack definitions.
File Description
languages/​swift/​custom/​test/​UnvalidatedUrlSchemeParameter/​UnvalidatedUrlSchemeParameter.qlref Connects deep-link tests to the query and expectation processor.
languages/​swift/​custom/​test/​UnvalidatedUrlSchemeParameter/​UnvalidatedUrlSchemeParameter.expected Records expected alerts and flow paths.
languages/​swift/​custom/​test/​UnvalidatedUrlSchemeParameter/​test.swift Covers delegate sources, sensitive sinks, and validation branches.
languages/​swift/​custom/​test/​UncheckedSubstringRange/​UncheckedSubstringRange.qlref Connects range tests to the query and expectation processor.
languages/​swift/​custom/​test/​UncheckedSubstringRange/​UncheckedSubstringRange.expected Records expected unchecked-range alerts.
languages/​swift/​custom/​test/​UncheckedSubstringRange/​test.swift Covers unchecked and checked delimiter searches.
languages/​swift/​custom/​test/​qlpack.yml Defines the Swift test pack.
languages/​swift/​custom/​src/​UnvalidatedUrlSchemeParameter/​UnvalidatedUrlSchemeParameter.ql Implements deep-link taint tracking and validation barriers.
languages/​swift/​custom/​src/​UnvalidatedUrlSchemeParameter/​UnvalidatedUrlSchemeParameter.md Explains deep-link risks and parameter validation.
languages/​swift/​custom/​src/​UncheckedSubstringRange/​UncheckedSubstringRange.ql Detects unchecked search results used as substring bounds.
languages/​swift/​custom/​src/​UncheckedSubstringRange/​UncheckedSubstringRange.md Documents range checks and safer parsing.
languages/​swift/​custom/​src/​qlpack.yml Defines the query pack and Swift library dependency.
languages/​swift/​custom/​.gitkeep Directory placeholder associated with the new pack.

Review effort: Balanced

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Query Create]: CWE-20 MEDIUM - Swift: new query for cwe 20

3 participants