Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added languages/swift/custom/.gitkeep
Empty file.
Original file line number Diff line number Diff line change
@@ -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: "<td>key</td><td>")
let searchToRange: NSRange? = (responseString as NSString?)?.range(of: "</td></tr></table>")
// 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: "<td>key</td><td>")
let searchToRange = ns.range(of: "</td></tr></table>")
// 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:)](<https://developer.apple.com/documentation/foundation/nsstring/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).
Original file line number Diff line number Diff line change
@@ -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."
Original file line number Diff line number Diff line change
@@ -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).
Loading
Loading