diff --git a/languages/swift/custom/.gitkeep b/languages/swift/custom/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/languages/swift/custom/src/UncheckedSubstringRange/UncheckedSubstringRange.md b/languages/swift/custom/src/UncheckedSubstringRange/UncheckedSubstringRange.md
new file mode 100644
index 00000000..8b9da7da
--- /dev/null
+++ b/languages/swift/custom/src/UncheckedSubstringRange/UncheckedSubstringRange.md
@@ -0,0 +1,45 @@
+# Unchecked substring range
+
+`NSString.range(of:)` returns a range whose `location` is `NSNotFound` (and whose `length` is `0`) when the text is not found. If the app uses that range to compute the bounds of a substring without checking for this case, input that does not contain the expected delimiter makes the computed bounds invalid. Calls such as `substring(with:)`, `substring(from:)` or `substring(to:)` then raise an `NSRangeException` and crash the app, or extract the wrong part of the string. This is a risk when the string comes from an untrusted source, such as a server response (CWE-20).
+
+## Recommendation
+
+Check the result of every `range(of:)` call before you use it. Compare `location` with `NSNotFound` (or check that `length` is not `0`), and check that the computed bounds are in order and inside the string. Better still, use a real parser for structured data such as HTML, JSON or XML.
+
+## Example
+
+In this example, the key is extracted from an HTTP response without checking that either delimiter was found:
+
+```swift
+func key(fromResponseString responseString: String?) -> String? {
+ let searchFromRange: NSRange? = (responseString as NSString?)?.range(of: "
key | ")
+ let searchToRange: NSRange? = (responseString as NSString?)?.range(of: " | ")
+ // BAD: if either delimiter is missing, the computed range is invalid
+ return (responseString as NSString?)?.substring(with: NSRange(
+ location: (searchFromRange?.location ?? 0) + (searchFromRange?.length ?? 0),
+ length: (searchToRange?.location ?? 0) - (searchFromRange?.location ?? 0) - (searchFromRange?.length ?? 0)))
+}
+```
+
+In this version, both lookups are checked before the substring is computed:
+
+```swift
+func key(fromResponseString responseString: String) -> String? {
+ let ns = responseString as NSString
+ let searchFromRange = ns.range(of: "key | ")
+ let searchToRange = ns.range(of: " | ")
+ // GOOD: both delimiters must be present and in order
+ guard searchFromRange.location != NSNotFound, searchToRange.location != NSNotFound else {
+ return nil
+ }
+ let start = searchFromRange.location + searchFromRange.length
+ guard searchToRange.location >= start else { return nil }
+ return ns.substring(with: NSRange(location: start, length: searchToRange.location - start))
+}
+```
+
+## References
+
+- Apple Developer Documentation: [range(of:)]().
+- Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).
+- Common Weakness Enumeration: [CWE-129](https://cwe.mitre.org/data/definitions/129.html).
diff --git a/languages/swift/custom/src/UncheckedSubstringRange/UncheckedSubstringRange.ql b/languages/swift/custom/src/UncheckedSubstringRange/UncheckedSubstringRange.ql
new file mode 100644
index 00000000..b6d12a63
--- /dev/null
+++ b/languages/swift/custom/src/UncheckedSubstringRange/UncheckedSubstringRange.ql
@@ -0,0 +1,173 @@
+/**
+ * @name Unchecked substring range
+ * @description Using the result of `NSString.range(of:)` to compute a substring
+ * without checking that the searched text was found can crash the app
+ * or extract the wrong data when the input does not have the expected
+ * format.
+ * @kind problem
+ * @problem.severity warning
+ * @security-severity 5.3
+ * @precision medium
+ * @id swift/unchecked-substring-range
+ * @tags security
+ * correctness
+ * external/cwe/cwe-020
+ * external/cwe/cwe-129
+ */
+
+import swift
+import codeql.swift.dataflow.DataFlow
+import codeql.swift.dataflow.TaintTracking
+import codeql.swift.controlflow.BasicBlocks
+import codeql.swift.controlflow.ControlFlowGraph
+
+/** A call to `NSString.range(of:)` or one of its overloads. */
+class NSStringRangeOfCall extends CallExpr {
+ NSStringRangeOfCall() {
+ exists(Method m |
+ this.getStaticTarget() = m and
+ m.getName().matches("range(of:%") and
+ m.getEnclosingDecl().asNominalTypeDecl().getABaseTypeDecl*().getName() = "NSString"
+ )
+ }
+}
+
+/** Gets `e` with any optional bindings and force unwraps removed. */
+private Expr stripped(Expr e) {
+ result = e and
+ not result instanceof BindOptionalExpr and
+ not result instanceof ForceValueExpr
+ or
+ result = stripped(e.(BindOptionalExpr).getSubExpr())
+ or
+ result = stripped(e.(ForceValueExpr).getSubExpr())
+}
+
+/** Holds if `ref` reads the `location` or `length` field of an `NSRange`. */
+private predicate isNSRangeFieldRead(MemberRefExpr ref) {
+ exists(VarDecl field |
+ field = ref.getMember() and
+ field.getName() = ["location", "length"] and
+ field.getEnclosingDecl().asNominalTypeDecl().getName() = ["_NSRange", "NSRange"]
+ )
+}
+
+/**
+ * Holds if the value of `e` is derived (in the same function) from the range
+ * returned by `call`, either directly or through its `location`/`length` fields.
+ */
+private predicate derivedFromRange(NSStringRangeOfCall call, Expr e) {
+ TaintTracking::localTaint(DataFlow::exprNode(call), DataFlow::exprNode(e))
+ or
+ derivedFromRangeField(call, e, _)
+}
+
+/**
+ * Holds if `e` is derived from the `location` or `length` field of the range
+ * returned by `call`.
+ */
+private predicate derivedFromRangeField(NSStringRangeOfCall call, Expr e, string fieldName) {
+ exists(MemberRefExpr ref |
+ isRangeFieldOfLookup(call, ref, fieldName) and
+ TaintTracking::localTaint(DataFlow::exprNode(ref), DataFlow::exprNode(e))
+ )
+}
+
+/** Holds if `field` directly reads the given range field from the result of `call`. */
+private predicate isRangeFieldOfLookup(NSStringRangeOfCall call, Expr field, string fieldName) {
+ exists(MemberRefExpr ref |
+ field = ref and
+ isNSRangeFieldRead(ref) and
+ ref.getMember().(VarDecl).getName() = fieldName and
+ TaintTracking::localTaint(DataFlow::exprNode(call), DataFlow::exprNode(stripped(ref.getBase())))
+ )
+}
+
+/**
+ * Holds if `arg` is an argument that is used as a position or range within a
+ * string, for example the argument of `NSString.substring(with:)` or of
+ * `NSRange(location:length:)`.
+ */
+private predicate isSubstringBoundArgument(Expr arg) {
+ exists(CallExpr c, Function f | c.getStaticTarget() = f |
+ (
+ f.getEnclosingDecl().asNominalTypeDecl().getABaseTypeDecl*().getName() = "NSString" and
+ f.getName() =
+ ["substring(with:)", "substring(from:)", "substring(to:)", "replacingCharacters(in:with:)"] and
+ arg = c.getArgument(0).getExpr()
+ or
+ f.(Initializer).getEnclosingDecl().asNominalTypeDecl().getName() = ["_NSRange", "NSRange"] and
+ f.getName() = "init(location:length:)" and
+ arg = c.getAnArgument().getExpr()
+ or
+ f.getName() = "NSMakeRange(_:_:)" and
+ arg = c.getAnArgument().getExpr()
+ )
+ )
+}
+
+/** Holds if `e` is the `NSNotFound` constant. */
+private predicate isNSNotFound(Expr e) {
+ e.(DeclRefExpr).getDecl().(VarDecl).getName() = "NSNotFound"
+}
+
+/** Holds if `e` is the integer literal `0`. */
+private predicate isZero(Expr e) {
+ e.(IntegerLiteralExpr).getStringValue() = "0"
+}
+
+/**
+ * Holds if `check` checks whether the range returned by `call` is present, and
+ * `passing` indicates whether a present range makes the check evaluate to true.
+ */
+private predicate isPresenceCheck(NSStringRangeOfCall call, Expr check, boolean passing) {
+ exists(BinaryExpr cmp, Expr value, Expr sentinel |
+ check = cmp and
+ (
+ cmp.getLeftOperand() = value and
+ cmp.getRightOperand() = sentinel
+ or
+ cmp.getRightOperand() = value and
+ cmp.getLeftOperand() = sentinel
+ ) and
+ (
+ isRangeFieldOfLookup(call, value, "location") and
+ isNSNotFound(sentinel) and
+ (
+ cmp.getStaticTarget().getName() = "!=(_:_:)" and passing = true
+ or
+ cmp.getStaticTarget().getName() = "==(_:_:)" and passing = false
+ )
+ or
+ isRangeFieldOfLookup(call, value, "length") and
+ isZero(sentinel) and
+ (
+ cmp.getStaticTarget().getName() = "!=(_:_:)" and passing = true
+ or
+ cmp.getStaticTarget().getName() = "==(_:_:)" and passing = false
+ )
+ )
+ )
+}
+
+/** Holds if a presence check's passing branch dominates this use of the range. */
+private predicate isCheckedBeforeUse(NSStringRangeOfCall call, Expr boundArgument) {
+ exists(ConditionBlock bb, Expr check, boolean passing |
+ check = bb.getLastNode().getNode().asAstNode() and
+ isPresenceCheck(call, check, passing) and
+ bb.edgeDominates(
+ DataFlow::exprNode(boundArgument).getCfgNode().getBasicBlock(),
+ any(BooleanSuccessor s | s.getValue() = passing)
+ )
+ )
+}
+
+from NSStringRangeOfCall call
+where
+ exists(Expr arg |
+ derivedFromRange(call, arg) and
+ isSubstringBoundArgument(arg) and
+ not isCheckedBeforeUse(call, arg)
+ )
+select call,
+ "This search result is used to compute a substring range without checking that the text was found."
diff --git a/languages/swift/custom/src/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.md b/languages/swift/custom/src/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.md
new file mode 100644
index 00000000..1cbd71ca
--- /dev/null
+++ b/languages/swift/custom/src/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.md
@@ -0,0 +1,50 @@
+# Unvalidated custom URL scheme parameter
+
+Any app or web page can open an iOS app through a custom URL scheme (for example `myapp://send?to=...&message=...`) and choose every part of that URL. The URL arrives in `UIApplicationDelegate.application(_:open:options:)` or `UISceneDelegate.scene(_:openURLContexts:)`. If the app uses the query parameters of that URL to show messages, fill in an SMS or email composer, or open other URLs without validating them, an attacker can trigger those actions with values the attacker chooses (CWE-20, CWE-939).
+
+## Recommendation
+
+Treat every component of a deep link as untrusted input. Validate each parameter before you use it. For example, check it against an allow list or a strict format such as a phone number pattern, and reject the link if any parameter fails the check. Checking only the URL scheme or host is not enough, because any caller can use your scheme.
+
+## Example
+
+In this example, the app only checks the scheme and then shows a message that includes the `message` and `contactNumber` query parameters:
+
+```swift
+func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
+ if url.scheme == "igoat", let queryInfo = url.parametersInfo {
+ let mobileNo = queryInfo["contactNumber"] ?? ""
+ let message = queryInfo["message"] ?? ""
+ // BAD: attacker-controlled values are shown to the user as-is
+ UIAlertController.showAlertWith(title: "iGoat", message: "Message \"\(message)\" sent to \(mobileNo)")
+ return true
+ }
+ return false
+}
+```
+
+In this version, each parameter is validated before it is used:
+
+```swift
+func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
+ guard url.scheme == "igoat", let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else {
+ return false
+ }
+ let number = items.first?.value ?? ""
+ let text = items.last?.value ?? ""
+ // GOOD: each parameter is checked before use
+ guard isValidPhoneNumber(number) else { return false }
+ if !allowedMessages.contains(text) { return false }
+ let composer = MFMessageComposeViewController()
+ composer.recipients = [number]
+ composer.body = text
+ return true
+}
+```
+
+## References
+
+- Apple Developer Documentation: [Defining a custom URL scheme for your app](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app).
+- OWASP MASTG: [Testing Deep Links](https://mas.owasp.org/MASTG/tests/ios/MASVS-PLATFORM/MASTG-TEST-0075/).
+- Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).
+- Common Weakness Enumeration: [CWE-939](https://cwe.mitre.org/data/definitions/939.html).
diff --git a/languages/swift/custom/src/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.ql b/languages/swift/custom/src/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.ql
new file mode 100644
index 00000000..30199b95
--- /dev/null
+++ b/languages/swift/custom/src/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.ql
@@ -0,0 +1,214 @@
+/**
+ * @name Unvalidated custom URL scheme parameter
+ * @description Using data from a custom URL scheme (deep link) to drive user-visible
+ * messages or actions without validating it allows other apps and web
+ * pages to trigger those actions with attacker-chosen values.
+ * @kind path-problem
+ * @problem.severity warning
+ * @security-severity 5.3
+ * @precision medium
+ * @id swift/unvalidated-url-scheme-parameter
+ * @tags security
+ * external/cwe/cwe-020
+ * external/cwe/cwe-939
+ */
+
+import swift
+import codeql.swift.dataflow.DataFlow
+import codeql.swift.dataflow.Ssa
+import codeql.swift.dataflow.TaintTracking
+import codeql.swift.controlflow.BasicBlocks
+import codeql.swift.controlflow.ControlFlowGraph
+import UnvalidatedUrlSchemeParameterFlow::PathGraph
+
+/**
+ * A parameter of a `UIApplicationDelegate` or `UISceneDelegate` method that iOS
+ * calls with the URL (or URL contexts) used to open the app through a custom URL
+ * scheme.
+ */
+class CustomUrlSchemeSource extends DataFlow::Node {
+ CustomUrlSchemeSource() {
+ exists(Method m, string protocol, string name, int i |
+ m.getEnclosingDecl().asNominalTypeDecl().getABaseTypeDecl*().(ProtocolDecl).getName() =
+ protocol and
+ m.getName() = name and
+ this.asParameter() = m.getParam(i)
+ |
+ protocol = "UIApplicationDelegate" and
+ name =
+ [
+ "application(_:open:options:)", "application(_:handleOpen:)",
+ "application(_:open:sourceApplication:annotation:)"
+ ] and
+ i = 1
+ or
+ protocol = "UISceneDelegate" and
+ name = "scene(_:openURLContexts:)" and
+ i = 1
+ or
+ protocol = "UISceneDelegate" and
+ name = "scene(_:willConnectTo:options:)" and
+ i = 2
+ )
+ }
+}
+
+/**
+ * A value that is shown to the user or that drives an action on the user's behalf.
+ */
+class UrlSchemeParameterSink extends DataFlow::Node {
+ string kind;
+
+ UrlSchemeParameterSink() {
+ // `UIAlertController(title:message:preferredStyle:)`
+ exists(CallExpr call, Initializer init |
+ call.getStaticTarget() = init and
+ init.getEnclosingDecl().asNominalTypeDecl().getName() = "UIAlertController" and
+ init.getName() = "init(title:message:preferredStyle:)" and
+ this.asExpr() = call.getArgument([0, 1]).getExpr() and
+ kind = "an alert"
+ )
+ or
+ // `MFMessageComposeViewController.recipients` / `.body` and
+ // `MFMailComposeViewController.setToRecipients(_:)` and similar.
+ exists(AssignExpr assign, MemberRefExpr ref |
+ assign.getDest() = ref and
+ not assign.getEnclosingFunction() instanceof Accessor and
+ ref.getMember().(VarDecl).getEnclosingDecl().asNominalTypeDecl().getName() =
+ "MFMessageComposeViewController" and
+ ref.getMember().(VarDecl).getName() = ["recipients", "body", "subject"] and
+ this.asExpr() = assign.getSource() and
+ kind = "a message composer"
+ )
+ or
+ exists(CallExpr call, Method m |
+ call.getStaticTarget() = m and
+ m.getEnclosingDecl().asNominalTypeDecl().getName() = "MFMailComposeViewController" and
+ m.getName() =
+ [
+ "setToRecipients(_:)", "setCcRecipients(_:)", "setBccRecipients(_:)", "setSubject(_:)",
+ "setMessageBody(_:isHTML:)"
+ ] and
+ this.asExpr() = call.getArgument(0).getExpr() and
+ kind = "a mail composer"
+ )
+ or
+ // `UIApplication.open(_:options:completionHandler:)` / `openURL(_:)`
+ exists(CallExpr call, Method m |
+ call.getStaticTarget() = m and
+ m.getEnclosingDecl().asNominalTypeDecl().getName() = "UIApplication" and
+ m.getName() = ["open(_:options:completionHandler:)", "openURL(_:)"] and
+ this.asExpr() = call.getArgument(0).getExpr() and
+ kind = "a URL opened by the app"
+ )
+ }
+
+ /** Gets a description of what this sink is. */
+ string getKind() { result = kind }
+}
+
+/** Gets `e` with any optional bindings and force unwraps removed. */
+private Expr stripped(Expr e) {
+ result = e and
+ not result instanceof BindOptionalExpr and
+ not result instanceof ForceValueExpr
+ or
+ result = stripped(e.(BindOptionalExpr).getSubExpr())
+ or
+ result = stripped(e.(ForceValueExpr).getSubExpr())
+}
+
+/**
+ * Holds if `check` is a `Bool`-valued call or an equality comparison that
+ * directly inspects the value of `v` (for example `isValid(v)`,
+ * `allowed.contains(v)`, `v.allSatisfy(...)` or `v == "expected"`), and `v` has
+ * passed the check when `check` evaluates to `passing`.
+ */
+private predicate validatesVariable(Expr check, VarDecl v, Expr validatedRead, boolean passing) {
+ exists(Expr operand | operand.(DeclRefExpr).getDecl() = v and validatedRead = operand |
+ check.getType().getName() = "Bool" and
+ (
+ operand = stripped(check.(CallExpr).getAnArgument().getExpr())
+ or
+ operand = stripped(check.(CallExpr).getQualifier())
+ ) and
+ passing = true
+ or
+ operand = stripped(check.(BinaryExpr).getAnOperand()) and
+ (
+ check.(BinaryExpr).getStaticTarget().getName() = ["==(_:_:)", "~=(_:_:)"] and
+ passing = true
+ or
+ check.(BinaryExpr).getStaticTarget().getName() = "!=(_:_:)" and
+ passing = false
+ )
+ )
+}
+
+/**
+ * A read of a variable that is only reachable after the variable has passed a
+ * validation check in an `if`/`guard`/`while` condition.
+ */
+class ValidatedVariableBarrier extends DataFlow::Node {
+ ValidatedVariableBarrier() {
+ exists(
+ ConditionBlock bb, Expr check, VarDecl v, Expr validatedRead, boolean passing,
+ Ssa::Definition def, ControlFlowNode checkRead, ControlFlowNode barrierRead
+ |
+ check = bb.getLastNode().getNode().asAstNode() and
+ validatesVariable(check, v, validatedRead, passing) and
+ this.asExpr().(DeclRefExpr).getDecl() = v and
+ checkRead = def.getARead() and
+ checkRead.getNode().asAstNode() = validatedRead and
+ barrierRead = def.getARead() and
+ barrierRead.getNode().asAstNode() = this.asExpr() and
+ bb.edgeDominates(this.getCfgNode().getBasicBlock(),
+ any(BooleanSuccessor s | s.getValue() = passing))
+ )
+ }
+}
+
+module UnvalidatedUrlSchemeParameterConfig implements DataFlow::ConfigSig {
+ predicate isSource(DataFlow::Node node) { node instanceof CustomUrlSchemeSource }
+
+ predicate isSink(DataFlow::Node node) { node instanceof UrlSchemeParameterSink }
+
+ predicate isBarrier(DataFlow::Node node) { node instanceof ValidatedVariableBarrier }
+
+ predicate isAdditionalFlowStep(DataFlow::Node pred, DataFlow::Node succ) {
+ // `URLComponents(url:resolvingAgainstBaseURL:)` and `URLComponents(string:)`
+ exists(CallExpr call, Initializer init |
+ call.getStaticTarget() = init and
+ init.getEnclosingDecl().asNominalTypeDecl().getName() = "URLComponents" and
+ pred.asExpr() = call.getArgument(0).getExpr() and
+ succ.asExpr() = call
+ )
+ or
+ // Members of `URLComponents` and `URLQueryItem`, for example `queryItems` and `value`.
+ exists(MemberRefExpr ref |
+ ref.getMember().(VarDecl).getEnclosingDecl().asNominalTypeDecl().getName() =
+ ["URLComponents", "URLQueryItem"] and
+ pred.asExpr() = ref.getBase() and
+ succ.asExpr() = ref
+ )
+ or
+ // Iterating over a tainted collection, for example `for context in URLContexts`.
+ exists(ForEachStmt for |
+ pred.asExpr() = [for.getSequence(), for.getSequence().(CallExpr).getQualifier()] and
+ succ.asPattern() = for.getPattern()
+ )
+ }
+
+ predicate observeDiffInformedIncrementalMode() { any() }
+}
+
+module UnvalidatedUrlSchemeParameterFlow =
+ TaintTracking::Global;
+
+from
+ UnvalidatedUrlSchemeParameterFlow::PathNode source,
+ UnvalidatedUrlSchemeParameterFlow::PathNode sink
+where UnvalidatedUrlSchemeParameterFlow::flowPath(source, sink)
+select sink.getNode(), source, sink,
+ "This value from a $@ reaches " + sink.getNode().(UrlSchemeParameterSink).getKind() +
+ " without being validated.", source.getNode(), "custom URL scheme parameter"
diff --git a/languages/swift/custom/src/qlpack.yml b/languages/swift/custom/src/qlpack.yml
new file mode 100644
index 00000000..397f59b7
--- /dev/null
+++ b/languages/swift/custom/src/qlpack.yml
@@ -0,0 +1,5 @@
+name: languages-swift-custom-src
+version: 0.0.2
+library: false
+dependencies:
+ codeql/swift-all: "*"
diff --git a/languages/swift/custom/test/UncheckedSubstringRange/UncheckedSubstringRange.expected b/languages/swift/custom/test/UncheckedSubstringRange/UncheckedSubstringRange.expected
new file mode 100644
index 00000000..7a3b6d91
--- /dev/null
+++ b/languages/swift/custom/test/UncheckedSubstringRange/UncheckedSubstringRange.expected
@@ -0,0 +1,8 @@
+| UncheckedSubstringRange/test.swift:35:35:35:67 | call to range(of:) | This search result is used to compute a substring range without checking that the text was found. |
+| UncheckedSubstringRange/test.swift:36:33:36:67 | call to range(of:) | This search result is used to compute a substring range without checking that the text was found. |
+| UncheckedSubstringRange/test.swift:43:11:43:26 | call to range(of:) | This search result is used to compute a substring range without checking that the text was found. |
+| UncheckedSubstringRange/test.swift:49:15:49:42 | call to range(of:options:) | This search result is used to compute a substring range without checking that the text was found. |
+| UncheckedSubstringRange/test.swift:55:26:55:41 | call to range(of:) | This search result is used to compute a substring range without checking that the text was found. |
+| UncheckedSubstringRange/test.swift:96:11:96:26 | call to range(of:) | This search result is used to compute a substring range without checking that the text was found. |
+| UncheckedSubstringRange/test.swift:108:11:108:26 | call to range(of:) | This search result is used to compute a substring range without checking that the text was found. |
+| UncheckedSubstringRange/test.swift:115:11:115:26 | call to range(of:) | This search result is used to compute a substring range without checking that the text was found. |
diff --git a/languages/swift/custom/test/UncheckedSubstringRange/UncheckedSubstringRange.qlref b/languages/swift/custom/test/UncheckedSubstringRange/UncheckedSubstringRange.qlref
new file mode 100644
index 00000000..9ecf21b1
--- /dev/null
+++ b/languages/swift/custom/test/UncheckedSubstringRange/UncheckedSubstringRange.qlref
@@ -0,0 +1,2 @@
+query: UncheckedSubstringRange/UncheckedSubstringRange.ql
+postprocess: utils/test/InlineExpectationsTestQuery.ql
diff --git a/languages/swift/custom/test/UncheckedSubstringRange/test.swift b/languages/swift/custom/test/UncheckedSubstringRange/test.swift
new file mode 100644
index 00000000..58ad3297
--- /dev/null
+++ b/languages/swift/custom/test/UncheckedSubstringRange/test.swift
@@ -0,0 +1,119 @@
+// --- stubs ---
+
+let NSNotFound: Int = Int.max
+
+struct _NSRange {
+ var location: Int
+ var length: Int
+ init(location: Int, length: Int) {
+ self.location = location
+ self.length = length
+ }
+}
+
+typealias NSRange = _NSRange
+
+func NSMakeRange(_ loc: Int, _ len: Int) -> NSRange {
+ return NSRange(location: loc, length: len)
+}
+
+class NSString {
+ init(string: String) {}
+ var length: Int { get { return 0 } }
+ func range(of searchString: String) -> NSRange { return NSRange(location: NSNotFound, length: 0) }
+ func range(of searchString: String, options mask: Int) -> NSRange { return NSRange(location: NSNotFound, length: 0) }
+ func substring(with range: NSRange) -> String { return "" }
+ func substring(from: Int) -> String { return "" }
+ func substring(to: Int) -> String { return "" }
+ func replacingCharacters(in range: NSRange, with replacement: String) -> String { return "" }
+}
+
+// --- tests ---
+
+// BAD: neither delimiter lookup is checked before computing the substring range.
+func key(fromResponseString responseString: String?) -> String? {
+ let ns = responseString.map { NSString(string: $0) }
+ let searchFromRange: NSRange? = ns?.range(of: "key | ") // $ Alert
+ let searchToRange: NSRange? = ns?.range(of: " | ") // $ Alert
+ let substring = ns?.substring(with: NSRange(location: Int((searchFromRange?.location ?? 0) + (searchFromRange?.length ?? 0)), length: Int((searchToRange?.location ?? 0) - (searchFromRange?.location ?? 0) - (searchFromRange?.length ?? 0))))
+ return substring
+}
+
+// BAD: the location of a missing delimiter is NSNotFound, so the offset overflows.
+func valueAfterEquals(_ s: NSString) -> String {
+ let r = s.range(of: "=") // $ Alert
+ return s.substring(from: r.location + r.length)
+}
+
+// BAD: unchecked range passed straight to `substring(with:)`.
+func betweenMarkers(_ s: NSString) -> String {
+ let start = s.range(of: "[", options: 0) // $ Alert
+ return s.substring(with: NSMakeRange(start.location + 1, 3))
+}
+
+// BAD: unchecked range used directly.
+func prefixUpTo(_ s: NSString) -> String {
+ return s.substring(to: s.range(of: ";").location) // $ Alert
+}
+
+// GOOD: both lookups are checked against NSNotFound.
+func keyChecked(fromResponseString responseString: String) -> String? {
+ let ns = NSString(string: responseString)
+ let searchFromRange = ns.range(of: "key | ")
+ let searchToRange = ns.range(of: " | ")
+ guard searchFromRange.location != NSNotFound, searchToRange.location != NSNotFound else {
+ return nil
+ }
+ let start = searchFromRange.location + searchFromRange.length
+ guard searchToRange.location >= start else {
+ return nil
+ }
+ return ns.substring(with: NSRange(location: start, length: searchToRange.location - start))
+}
+
+// GOOD: the length of the match is checked.
+func valueAfterEqualsChecked(_ s: NSString) -> String? {
+ let r = s.range(of: "=")
+ if r.length == 0 {
+ return nil
+ }
+ return s.substring(from: r.location + r.length)
+}
+
+// GOOD: the range is only used to test whether the delimiter is present.
+func hasDelimiter(_ s: NSString) -> Bool {
+ return s.range(of: "=").location != NSNotFound
+}
+
+// GOOD: the range is not used to compute a substring.
+func delimiterPosition(_ s: NSString) -> Int {
+ let r = s.range(of: "=")
+ return r.location
+}
+
+// BAD: the range argument of `replacingCharacters(in:with:)` is unchecked.
+func replaceUsingUncheckedRange(_ s: NSString) -> String {
+ let r = s.range(of: "=") // $ Alert
+ return s.replacingCharacters(in: r, with: "replacement")
+}
+
+// GOOD: the lookup is only used to build replacement text, not the range.
+func replaceUsingLookupInReplacement(_ s: NSString) -> String {
+ let r = s.range(of: "=")
+ return s.replacingCharacters(in: NSRange(location: 0, length: 1), with: "\(r.location)")
+}
+
+// BAD: an ordering check does not establish that the delimiter was found.
+func orderingCheckIsNotPresence(_ s: NSString) -> String? {
+ let r = s.range(of: "=") // $ Alert
+ guard r.location > 0 else { return nil }
+ return s.substring(from: r.location + r.length)
+}
+
+// BAD: the lookup is used before the presence check.
+func presenceCheckAfterUse(_ s: NSString) -> String? {
+ let r = s.range(of: "=") // $ Alert
+ let value = s.substring(from: r.location + r.length)
+ guard r.location != NSNotFound else { return nil }
+ return value
+}
diff --git a/languages/swift/custom/test/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.expected b/languages/swift/custom/test/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.expected
new file mode 100644
index 00000000..704874e4
--- /dev/null
+++ b/languages/swift/custom/test/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.expected
@@ -0,0 +1,115 @@
+#select
+| UnvalidatedUrlSchemeParameter/test.swift:96:68:96:68 | message | UnvalidatedUrlSchemeParameter/test.swift:111:42:111:52 | url | UnvalidatedUrlSchemeParameter/test.swift:96:68:96:68 | message | This value from a $@ reaches an alert without being validated. | UnvalidatedUrlSchemeParameter/test.swift:111:42:111:52 | url | custom URL scheme parameter |
+| UnvalidatedUrlSchemeParameter/test.swift:131:27:131:34 | [...] | UnvalidatedUrlSchemeParameter/test.swift:124:42:124:52 | url | UnvalidatedUrlSchemeParameter/test.swift:131:27:131:34 | [...] | This value from a $@ reaches a message composer without being validated. | UnvalidatedUrlSchemeParameter/test.swift:124:42:124:52 | url | custom URL scheme parameter |
+| UnvalidatedUrlSchemeParameter/test.swift:132:21:132:21 | text | UnvalidatedUrlSchemeParameter/test.swift:124:42:124:52 | url | UnvalidatedUrlSchemeParameter/test.swift:132:21:132:21 | text | This value from a $@ reaches a message composer without being validated. | UnvalidatedUrlSchemeParameter/test.swift:124:42:124:52 | url | custom URL scheme parameter |
+| UnvalidatedUrlSchemeParameter/test.swift:134:33:134:33 | target | UnvalidatedUrlSchemeParameter/test.swift:124:42:124:52 | url | UnvalidatedUrlSchemeParameter/test.swift:134:33:134:33 | target | This value from a $@ reaches a URL opened by the app without being validated. | UnvalidatedUrlSchemeParameter/test.swift:124:42:124:52 | url | custom URL scheme parameter |
+| UnvalidatedUrlSchemeParameter/test.swift:187:27:187:27 | body | UnvalidatedUrlSchemeParameter/test.swift:180:42:180:52 | url | UnvalidatedUrlSchemeParameter/test.swift:187:27:187:27 | body | This value from a $@ reaches a mail composer without being validated. | UnvalidatedUrlSchemeParameter/test.swift:180:42:180:52 | url | custom URL scheme parameter |
+| UnvalidatedUrlSchemeParameter/test.swift:198:53:198:53 | query | UnvalidatedUrlSchemeParameter/test.swift:195:32:195:81 | URLContexts | UnvalidatedUrlSchemeParameter/test.swift:198:53:198:53 | query | This value from a $@ reaches an alert without being validated. | UnvalidatedUrlSchemeParameter/test.swift:195:32:195:81 | URLContexts | custom URL scheme parameter |
+| UnvalidatedUrlSchemeParameter/test.swift:205:33:205:41 | .url | UnvalidatedUrlSchemeParameter/test.swift:203:71:203:106 | connectionOptions | UnvalidatedUrlSchemeParameter/test.swift:205:33:205:41 | .url | This value from a $@ reaches a URL opened by the app without being validated. | UnvalidatedUrlSchemeParameter/test.swift:203:71:203:106 | connectionOptions | custom URL scheme parameter |
+| UnvalidatedUrlSchemeParameter/test.swift:218:63:218:63 | number | UnvalidatedUrlSchemeParameter/test.swift:212:42:212:52 | url | UnvalidatedUrlSchemeParameter/test.swift:218:63:218:63 | number | This value from a $@ reaches an alert without being validated. | UnvalidatedUrlSchemeParameter/test.swift:212:42:212:52 | url | custom URL scheme parameter |
+| UnvalidatedUrlSchemeParameter/test.swift:222:33:222:33 | url | UnvalidatedUrlSchemeParameter/test.swift:212:42:212:52 | url | UnvalidatedUrlSchemeParameter/test.swift:222:33:222:33 | url | This value from a $@ reaches a URL opened by the app without being validated. | UnvalidatedUrlSchemeParameter/test.swift:212:42:212:52 | url | custom URL scheme parameter |
+edges
+| UnvalidatedUrlSchemeParameter/test.swift:13:7:13:7 | self | file://:0:0:0:0 | self | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:95:43:95:52 | message | UnvalidatedUrlSchemeParameter/test.swift:96:68:96:68 | message | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:111:42:111:52 | url | UnvalidatedUrlSchemeParameter/test.swift:115:68:115:68 | "..." | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:115:68:115:68 | "..." | UnvalidatedUrlSchemeParameter/test.swift:95:43:95:52 | message | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:124:42:124:52 | url | UnvalidatedUrlSchemeParameter/test.swift:125:42:125:42 | url | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:125:23:125:77 | call to URLComponents.init(url:resolvingAgainstBaseURL:) | UnvalidatedUrlSchemeParameter/test.swift:125:23:125:78 | ...? | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:125:23:125:78 | ...? | UnvalidatedUrlSchemeParameter/test.swift:125:23:125:80 | .queryItems | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:125:23:125:80 | .queryItems | UnvalidatedUrlSchemeParameter/test.swift:128:18:128:29 | ...? | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:125:23:125:80 | .queryItems | UnvalidatedUrlSchemeParameter/test.swift:129:16:129:26 | ...? | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:125:42:125:42 | url | UnvalidatedUrlSchemeParameter/test.swift:125:23:125:77 | call to URLComponents.init(url:resolvingAgainstBaseURL:) | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:128:18:128:29 | ...? | UnvalidatedUrlSchemeParameter/test.swift:13:7:13:7 | self | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:128:18:128:29 | ...? | UnvalidatedUrlSchemeParameter/test.swift:128:18:128:31 | .value | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:128:18:128:31 | .value | UnvalidatedUrlSchemeParameter/test.swift:131:28:131:28 | number | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:128:18:128:31 | .value | UnvalidatedUrlSchemeParameter/test.swift:133:33:133:42 | ... .+(_:_:) ... | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:129:16:129:26 | ...? | UnvalidatedUrlSchemeParameter/test.swift:13:7:13:7 | self | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:129:16:129:26 | ...? | UnvalidatedUrlSchemeParameter/test.swift:129:16:129:28 | .value | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:129:16:129:28 | .value | UnvalidatedUrlSchemeParameter/test.swift:132:21:132:21 | text | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:131:28:131:28 | number | UnvalidatedUrlSchemeParameter/test.swift:131:27:131:34 | [...] | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:133:8:133:12 | let ...? [some:0] | UnvalidatedUrlSchemeParameter/test.swift:133:12:133:12 | target | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:133:12:133:12 | target | UnvalidatedUrlSchemeParameter/test.swift:134:33:134:33 | target | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:133:21:133:48 | call to URL.init(string:) [some:0] | UnvalidatedUrlSchemeParameter/test.swift:133:8:133:12 | let ...? [some:0] | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:133:33:133:42 | ... .+(_:_:) ... | UnvalidatedUrlSchemeParameter/test.swift:133:21:133:48 | call to URL.init(string:) [some:0] | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:180:42:180:52 | url | UnvalidatedUrlSchemeParameter/test.swift:181:36:181:36 | url | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:181:17:181:71 | call to URLComponents.init(url:resolvingAgainstBaseURL:) | UnvalidatedUrlSchemeParameter/test.swift:181:17:181:72 | ...? | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:181:17:181:72 | ...? | UnvalidatedUrlSchemeParameter/test.swift:181:17:181:74 | .queryItems | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:181:17:181:74 | .queryItems | UnvalidatedUrlSchemeParameter/test.swift:183:16:183:26 | ...? | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:181:36:181:36 | url | UnvalidatedUrlSchemeParameter/test.swift:181:17:181:71 | call to URLComponents.init(url:resolvingAgainstBaseURL:) | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:183:16:183:26 | ...? | UnvalidatedUrlSchemeParameter/test.swift:13:7:13:7 | self | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:183:16:183:26 | ...? | UnvalidatedUrlSchemeParameter/test.swift:183:16:183:28 | .value | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:183:16:183:28 | .value | UnvalidatedUrlSchemeParameter/test.swift:187:27:187:27 | body | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:195:32:195:81 | URLContexts | UnvalidatedUrlSchemeParameter/test.swift:196:20:196:20 | URLContexts | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:196:9:196:9 | context | UnvalidatedUrlSchemeParameter/test.swift:198:53:198:53 | query | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:196:20:196:20 | URLContexts | UnvalidatedUrlSchemeParameter/test.swift:196:9:196:9 | context | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:203:71:203:106 | connectionOptions | UnvalidatedUrlSchemeParameter/test.swift:205:33:205:41 | .url | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:212:42:212:52 | url | UnvalidatedUrlSchemeParameter/test.swift:213:42:213:42 | url | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:213:11:213:15 | let ...? [some:0] | UnvalidatedUrlSchemeParameter/test.swift:213:15:213:15 | comps | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:213:15:213:15 | comps | UnvalidatedUrlSchemeParameter/test.swift:216:18:216:18 | comps | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:213:23:213:77 | call to URLComponents.init(url:resolvingAgainstBaseURL:) | UnvalidatedUrlSchemeParameter/test.swift:213:23:213:77 | call to URLComponents.init(url:resolvingAgainstBaseURL:) [some:0] | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:213:23:213:77 | call to URLComponents.init(url:resolvingAgainstBaseURL:) | UnvalidatedUrlSchemeParameter/test.swift:216:18:216:18 | comps | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:213:23:213:77 | call to URLComponents.init(url:resolvingAgainstBaseURL:) [some:0] | UnvalidatedUrlSchemeParameter/test.swift:213:11:213:15 | let ...? [some:0] | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:213:42:213:42 | url | UnvalidatedUrlSchemeParameter/test.swift:213:23:213:77 | call to URLComponents.init(url:resolvingAgainstBaseURL:) | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:213:42:213:42 | url | UnvalidatedUrlSchemeParameter/test.swift:222:33:222:33 | url | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:216:18:216:18 | comps | UnvalidatedUrlSchemeParameter/test.swift:216:18:216:24 | .queryItems | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:216:18:216:24 | .queryItems | UnvalidatedUrlSchemeParameter/test.swift:216:18:216:41 | ...? | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:216:18:216:41 | ...? | UnvalidatedUrlSchemeParameter/test.swift:13:7:13:7 | self | provenance | |
+| UnvalidatedUrlSchemeParameter/test.swift:216:18:216:41 | ...? | UnvalidatedUrlSchemeParameter/test.swift:216:18:216:43 | .value | provenance | Config |
+| UnvalidatedUrlSchemeParameter/test.swift:216:18:216:43 | .value | UnvalidatedUrlSchemeParameter/test.swift:218:63:218:63 | number | provenance | |
+| file://:0:0:0:0 | self | file://:0:0:0:0 | .value | provenance | Config |
+nodes
+| UnvalidatedUrlSchemeParameter/test.swift:13:7:13:7 | self | semmle.label | self |
+| UnvalidatedUrlSchemeParameter/test.swift:95:43:95:52 | message | semmle.label | message |
+| UnvalidatedUrlSchemeParameter/test.swift:96:68:96:68 | message | semmle.label | message |
+| UnvalidatedUrlSchemeParameter/test.swift:111:42:111:52 | url | semmle.label | url |
+| UnvalidatedUrlSchemeParameter/test.swift:115:68:115:68 | "..." | semmle.label | "..." |
+| UnvalidatedUrlSchemeParameter/test.swift:124:42:124:52 | url | semmle.label | url |
+| UnvalidatedUrlSchemeParameter/test.swift:125:23:125:77 | call to URLComponents.init(url:resolvingAgainstBaseURL:) | semmle.label | call to URLComponents.init(url:resolvingAgainstBaseURL:) |
+| UnvalidatedUrlSchemeParameter/test.swift:125:23:125:78 | ...? | semmle.label | ...? |
+| UnvalidatedUrlSchemeParameter/test.swift:125:23:125:80 | .queryItems | semmle.label | .queryItems |
+| UnvalidatedUrlSchemeParameter/test.swift:125:42:125:42 | url | semmle.label | url |
+| UnvalidatedUrlSchemeParameter/test.swift:128:18:128:29 | ...? | semmle.label | ...? |
+| UnvalidatedUrlSchemeParameter/test.swift:128:18:128:31 | .value | semmle.label | .value |
+| UnvalidatedUrlSchemeParameter/test.swift:129:16:129:26 | ...? | semmle.label | ...? |
+| UnvalidatedUrlSchemeParameter/test.swift:129:16:129:28 | .value | semmle.label | .value |
+| UnvalidatedUrlSchemeParameter/test.swift:131:27:131:34 | [...] | semmle.label | [...] |
+| UnvalidatedUrlSchemeParameter/test.swift:131:28:131:28 | number | semmle.label | number |
+| UnvalidatedUrlSchemeParameter/test.swift:132:21:132:21 | text | semmle.label | text |
+| UnvalidatedUrlSchemeParameter/test.swift:133:8:133:12 | let ...? [some:0] | semmle.label | let ...? [some:0] |
+| UnvalidatedUrlSchemeParameter/test.swift:133:12:133:12 | target | semmle.label | target |
+| UnvalidatedUrlSchemeParameter/test.swift:133:21:133:48 | call to URL.init(string:) [some:0] | semmle.label | call to URL.init(string:) [some:0] |
+| UnvalidatedUrlSchemeParameter/test.swift:133:33:133:42 | ... .+(_:_:) ... | semmle.label | ... .+(_:_:) ... |
+| UnvalidatedUrlSchemeParameter/test.swift:134:33:134:33 | target | semmle.label | target |
+| UnvalidatedUrlSchemeParameter/test.swift:180:42:180:52 | url | semmle.label | url |
+| UnvalidatedUrlSchemeParameter/test.swift:181:17:181:71 | call to URLComponents.init(url:resolvingAgainstBaseURL:) | semmle.label | call to URLComponents.init(url:resolvingAgainstBaseURL:) |
+| UnvalidatedUrlSchemeParameter/test.swift:181:17:181:72 | ...? | semmle.label | ...? |
+| UnvalidatedUrlSchemeParameter/test.swift:181:17:181:74 | .queryItems | semmle.label | .queryItems |
+| UnvalidatedUrlSchemeParameter/test.swift:181:36:181:36 | url | semmle.label | url |
+| UnvalidatedUrlSchemeParameter/test.swift:183:16:183:26 | ...? | semmle.label | ...? |
+| UnvalidatedUrlSchemeParameter/test.swift:183:16:183:28 | .value | semmle.label | .value |
+| UnvalidatedUrlSchemeParameter/test.swift:187:27:187:27 | body | semmle.label | body |
+| UnvalidatedUrlSchemeParameter/test.swift:195:32:195:81 | URLContexts | semmle.label | URLContexts |
+| UnvalidatedUrlSchemeParameter/test.swift:196:9:196:9 | context | semmle.label | context |
+| UnvalidatedUrlSchemeParameter/test.swift:196:20:196:20 | URLContexts | semmle.label | URLContexts |
+| UnvalidatedUrlSchemeParameter/test.swift:198:53:198:53 | query | semmle.label | query |
+| UnvalidatedUrlSchemeParameter/test.swift:203:71:203:106 | connectionOptions | semmle.label | connectionOptions |
+| UnvalidatedUrlSchemeParameter/test.swift:205:33:205:41 | .url | semmle.label | .url |
+| UnvalidatedUrlSchemeParameter/test.swift:212:42:212:52 | url | semmle.label | url |
+| UnvalidatedUrlSchemeParameter/test.swift:213:11:213:15 | let ...? [some:0] | semmle.label | let ...? [some:0] |
+| UnvalidatedUrlSchemeParameter/test.swift:213:15:213:15 | comps | semmle.label | comps |
+| UnvalidatedUrlSchemeParameter/test.swift:213:23:213:77 | call to URLComponents.init(url:resolvingAgainstBaseURL:) | semmle.label | call to URLComponents.init(url:resolvingAgainstBaseURL:) |
+| UnvalidatedUrlSchemeParameter/test.swift:213:23:213:77 | call to URLComponents.init(url:resolvingAgainstBaseURL:) [some:0] | semmle.label | call to URLComponents.init(url:resolvingAgainstBaseURL:) [some:0] |
+| UnvalidatedUrlSchemeParameter/test.swift:213:42:213:42 | url | semmle.label | url |
+| UnvalidatedUrlSchemeParameter/test.swift:216:18:216:18 | comps | semmle.label | comps |
+| UnvalidatedUrlSchemeParameter/test.swift:216:18:216:24 | .queryItems | semmle.label | .queryItems |
+| UnvalidatedUrlSchemeParameter/test.swift:216:18:216:41 | ...? | semmle.label | ...? |
+| UnvalidatedUrlSchemeParameter/test.swift:216:18:216:43 | .value | semmle.label | .value |
+| UnvalidatedUrlSchemeParameter/test.swift:218:63:218:63 | number | semmle.label | number |
+| UnvalidatedUrlSchemeParameter/test.swift:222:33:222:33 | url | semmle.label | url |
+| file://:0:0:0:0 | .value | semmle.label | .value |
+| file://:0:0:0:0 | self | semmle.label | self |
+subpaths
+| UnvalidatedUrlSchemeParameter/test.swift:128:18:128:29 | ...? | UnvalidatedUrlSchemeParameter/test.swift:13:7:13:7 | self | file://:0:0:0:0 | .value | UnvalidatedUrlSchemeParameter/test.swift:128:18:128:31 | .value |
+| UnvalidatedUrlSchemeParameter/test.swift:129:16:129:26 | ...? | UnvalidatedUrlSchemeParameter/test.swift:13:7:13:7 | self | file://:0:0:0:0 | .value | UnvalidatedUrlSchemeParameter/test.swift:129:16:129:28 | .value |
+| UnvalidatedUrlSchemeParameter/test.swift:183:16:183:26 | ...? | UnvalidatedUrlSchemeParameter/test.swift:13:7:13:7 | self | file://:0:0:0:0 | .value | UnvalidatedUrlSchemeParameter/test.swift:183:16:183:28 | .value |
+| UnvalidatedUrlSchemeParameter/test.swift:216:18:216:41 | ...? | UnvalidatedUrlSchemeParameter/test.swift:13:7:13:7 | self | file://:0:0:0:0 | .value | UnvalidatedUrlSchemeParameter/test.swift:216:18:216:43 | .value |
diff --git a/languages/swift/custom/test/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.qlref b/languages/swift/custom/test/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.qlref
new file mode 100644
index 00000000..b7005ebe
--- /dev/null
+++ b/languages/swift/custom/test/UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.qlref
@@ -0,0 +1,2 @@
+query: UnvalidatedUrlSchemeParameter/UnvalidatedUrlSchemeParameter.ql
+postprocess: utils/test/InlineExpectationsTestQuery.ql
diff --git a/languages/swift/custom/test/UnvalidatedUrlSchemeParameter/test.swift b/languages/swift/custom/test/UnvalidatedUrlSchemeParameter/test.swift
new file mode 100644
index 00000000..aae60fa4
--- /dev/null
+++ b/languages/swift/custom/test/UnvalidatedUrlSchemeParameter/test.swift
@@ -0,0 +1,245 @@
+// --- stubs ---
+
+struct URL {
+ init?(string: String) {}
+ var scheme: String? { get { return nil } }
+ var host: String? { get { return nil } }
+ var query: String? { get { return nil } }
+ var absoluteString: String { get { return "" } }
+}
+
+struct URLQueryItem {
+ var name: String
+ var value: String?
+}
+
+struct URLComponents {
+ init?(url: URL, resolvingAgainstBaseURL resolve: Bool) {}
+ var queryItems: [URLQueryItem]? { get { return nil } }
+}
+
+class UIResponder {}
+class UIViewController : UIResponder {}
+
+class UIApplication {
+ struct OpenURLOptionsKey : Hashable {
+ let rawValue: String
+ }
+ struct LaunchOptionsKey : Hashable {
+ let rawValue: String
+ }
+ struct OpenExternalURLOptionsKey : Hashable {
+ let rawValue: String
+ }
+ static var shared: UIApplication { get { return UIApplication() } }
+ func open(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:], completionHandler completion: ((Bool) -> Void)? = nil) {}
+}
+
+protocol UIApplicationDelegate {
+ func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool
+}
+
+class UIAlertController : UIViewController {
+ enum Style { case actionSheet, alert }
+ init(title: String?, message: String?, preferredStyle: UIAlertController.Style) {}
+}
+
+class MFMessageComposeViewController : UIViewController {
+ var recipients: [String]?
+ var body: String?
+}
+
+class MFMailComposeViewController : UIViewController {
+ func setToRecipients(_ toRecipients: [String]?) {}
+ func setSubject(_ subject: String) {}
+ func setMessageBody(_ body: String, isHTML: Bool) {}
+}
+
+class UIScene : UIResponder {
+ class ConnectionOptions {
+ var urlContexts: Set { get { return [] } }
+ }
+}
+
+class UISceneSession {}
+
+class UIOpenURLContext : Hashable {
+ var url: URL { get { return URL(string: "")! } }
+ static func == (lhs: UIOpenURLContext, rhs: UIOpenURLContext) -> Bool { return lhs === rhs }
+ func hash(into hasher: inout Hasher) {}
+}
+
+protocol UISceneDelegate {
+ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
+ func scene(_ scene: UIScene, openURLContexts URLContexts: Set)
+}
+
+// --- helpers (mirroring common app extensions) ---
+
+extension URL {
+ var parametersInfo: [AnyHashable: Any]? {
+ let urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: false)
+ let queryItems = urlComponents?.queryItems
+ var queryStringDictionary = [String: String]()
+ for queryItem: URLQueryItem? in queryItems ?? [URLQueryItem?]() {
+ if let name = queryItem?.name {
+ let value = queryItem?.value != nil ? queryItem?.value : ""
+ queryStringDictionary[name] = value
+ }
+ }
+ return queryStringDictionary
+ }
+}
+
+extension UIAlertController {
+ class func showAlertWith(title: String, message: String) -> UIAlertController {
+ let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) // $ Alert
+ return alertController
+ }
+}
+
+func isValidPhoneNumber(_ number: String) -> Bool {
+ return number.allSatisfy { $0.isNumber } && number.count <= 15
+}
+
+let allowedMessages = ["Hello", "Goodbye"]
+
+// --- tests ---
+
+class AppDelegate1 : UIResponder, UIApplicationDelegate {
+ // BAD: only the scheme is checked; query parameters are used as-is.
+ func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { // $ Source
+ if url.scheme == "igoat", let queryInfo = url.parametersInfo {
+ let mobileNo = queryInfo["contactNumber"] ?? ""
+ let message = queryInfo["message"] ?? ""
+ _ = UIAlertController.showAlertWith(title: "iGoat", message: "Message \"\(message)\" sent to \(mobileNo)")
+ return true
+ }
+ return false
+ }
+}
+
+class AppDelegate2 : UIResponder, UIApplicationDelegate {
+ // BAD: query items drive an SMS composer and an outgoing URL open.
+ func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { // $ Source
+ guard let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else {
+ return false
+ }
+ let number = items.first?.value ?? ""
+ let text = items.last?.value ?? ""
+ let composer = MFMessageComposeViewController()
+ composer.recipients = [number] // $ Alert
+ composer.body = text // $ Alert
+ if let target = URL(string: "tel:" + number) {
+ UIApplication.shared.open(target) // $ Alert
+ }
+ return true
+ }
+}
+
+class AppDelegate3 : UIResponder, UIApplicationDelegate {
+ // GOOD: each parameter is validated before use.
+ func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
+ guard url.scheme == "igoat", let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else {
+ return false
+ }
+ let number = items.first?.value ?? ""
+ let text = items.last?.value ?? ""
+ guard isValidPhoneNumber(number) else {
+ return false
+ }
+ if !allowedMessages.contains(text) {
+ return false
+ }
+ let composer = MFMessageComposeViewController()
+ composer.recipients = [number]
+ composer.body = text
+ _ = UIAlertController(title: "Sent", message: text + " sent to " + number, preferredStyle: .alert)
+ return true
+ }
+}
+
+class AppDelegate4 : UIResponder, UIApplicationDelegate {
+ // GOOD: the URL contents are not used in a sensitive sink.
+ func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
+ _ = UIAlertController(title: "iGoat", message: "Link opened", preferredStyle: .alert)
+ return url.scheme == "igoat"
+ }
+}
+
+class NotADelegate {
+ // GOOD: not a custom URL scheme handler.
+ func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
+ _ = UIAlertController(title: "Info", message: url.absoluteString, preferredStyle: .alert)
+ return true
+ }
+}
+
+class AppDelegate5 : UIResponder, UIApplicationDelegate {
+ // BAD: the phone number is validated, but the mail body is not.
+ func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { // $ Source
+ let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
+ let number = items.first?.value ?? ""
+ let body = items.last?.value ?? ""
+ if isValidPhoneNumber(number) {
+ let mail = MFMailComposeViewController()
+ mail.setSubject("Call " + number)
+ mail.setMessageBody(body, isHTML: true) // $ Alert
+ }
+ return true
+ }
+}
+
+class SceneDelegate1 : UIResponder, UISceneDelegate {
+ // BAD: URL contexts delivered to a scene are used without validation.
+ func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { // $ Source
+ for context in URLContexts {
+ let query = context.url.query ?? ""
+ _ = UIAlertController(title: "Link", message: query, preferredStyle: .alert) // $ Alert
+ }
+ }
+
+ // BAD: URL contexts delivered when the scene is first connected.
+ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // $ Source
+ if let context = connectionOptions.urlContexts.first {
+ UIApplication.shared.open(context.url) // $ Alert
+ }
+ }
+}
+
+class AppDelegate6 : UIResponder, UIApplicationDelegate {
+ // BAD: parsing the URL is not validation, and the failed-validation branch uses the value.
+ func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { // $ Source
+ guard let comps = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
+ return false
+ }
+ let number = comps.queryItems?.first?.value ?? ""
+ guard isValidPhoneNumber(number) else {
+ _ = UIAlertController(title: "Invalid number", message: number, preferredStyle: .alert) // $ Alert
+ return false
+ }
+ if number != "112" {
+ UIApplication.shared.open(url) // $ Alert
+ } else {
+ _ = UIAlertController(title: "Calling", message: number, preferredStyle: .alert)
+ }
+ return true
+ }
+}
+
+class AppDelegate7 : UIResponder, UIApplicationDelegate {
+ // BAD: the validated mutable value is replaced with unvalidated input.
+ func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { // $ Source
+ guard let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else {
+ return false
+ }
+ var text = items.last?.value ?? ""
+ guard allowedMessages.contains(text) else {
+ return false
+ }
+ text = items.first?.value ?? ""
+ let composer = MFMessageComposeViewController()
+ composer.body = text // $ Alert
+ return true
+ }
+}
diff --git a/languages/swift/custom/test/qlpack.yml b/languages/swift/custom/test/qlpack.yml
new file mode 100644
index 00000000..8f8e1af6
--- /dev/null
+++ b/languages/swift/custom/test/qlpack.yml
@@ -0,0 +1,5 @@
+name: languages-swift-custom-test
+version: 0.0.2
+dependencies:
+ languages-swift-custom-src: ${workspace}
+extractor: swift