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
3 changes: 2 additions & 1 deletion .github/workflows/codeql-qlt-unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ jobs:
# The `ql` language (i.e. ql for ql) is always a special case.
# The `actions` language is currently not supported by `qlt` but is supported by `codeql`.
# TODO: Implement support for `actions` language in `qlt`
if [[ "$lang" == "ql" || "$lang" == "actions" ]]; then
# The `swift` extractor only supports macOS, so its tests cannot run on `ubuntu-latest`.
if [[ "$lang" == "ql" || "$lang" == "actions" || "$lang" == "swift" ]]; then
echo "⚠️ qlt unit testing is not currently supported for language: $lang"
continue
fi
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Fixed crypto key length may exceed the key buffer

CommonCrypto's `CCCrypt` reads the number of key bytes supplied as its key-length argument. Passing a caller-supplied `Data` buffer with a fixed AES-128 key length can read past the end when the buffer contains fewer than 16 bytes.

## Recommendation

Validate that the key buffer contains at least the number of bytes passed to `CCCrypt`, or derive the length from the same buffer.

## Example

```swift
func encrypt(keyData: Data) {
let keyLength = size_t(kCCKeySizeAES128)
keyData.withUnsafeBytes { keyBytes in
// BAD: `keyData` may contain fewer than 16 bytes.
CCCrypt(operation, algorithm, options, keyBytes, keyLength, ...)
}
}
```

Check the buffer before passing its pointer:

```swift
func encrypt(keyData: Data) {
guard keyData.count >= kCCKeySizeAES128 else { return }
let keyLength = size_t(kCCKeySizeAES128)
keyData.withUnsafeBytes { keyBytes in
CCCrypt(operation, algorithm, options, keyBytes, keyLength, ...)
}
}
```

## Known limitations

The query recognizes direct `CCCrypt` calls using a caller-supplied `Data`/`NSData` key or a `Data` value created from a `String` parameter. It recognizes the fixed `kCCKeySizeAES128` value and dominating comparisons with that key buffer's `count` on the left-hand side. Key buffers passed through other wrappers, aliases, or APIs are not analyzed.

## References

- Common Weakness Enumeration: [CWE-125](https://cwe.mitre.org/data/definitions/125.html).
- Common Weakness Enumeration: [CWE-823](https://cwe.mitre.org/data/definitions/823.html).
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* @name Fixed crypto key length may exceed the key buffer
* @description Passing a caller-supplied key buffer to CommonCrypto with a fixed key length
* can read beyond the end of the buffer.
* @kind problem
* @problem.severity warning
* @security-severity 6.5
* @precision medium
* @id swift/untrusted-crypto-key-length
* @tags security
* external/cwe/cwe-125
* external/cwe/cwe-823
*/

import swift
import codeql.swift.controlflow.BasicBlocks
import codeql.swift.controlflow.CfgNodes
import codeql.swift.controlflow.ControlFlowGraph

private predicate isCallerSuppliedKey(Expr dataExpr) {
exists(DeclRefExpr ref, ParamDecl param |
dataExpr = ref and
ref.getDecl() = param and
param.getType().getUnderlyingType().getName() = ["Data", "NSData"]
)
or
exists(
DeclRefExpr ref, VarDecl local, ApplyExpr conversion, DeclRefExpr inputRef, ParamDecl param
|
dataExpr = ref and
ref.getDecl() = local and
local.getType().getUnderlyingType().getName() = "Data" and
conversion = local.getParentInitializer() and
conversion.getQualifier() = inputRef and
inputRef.getDecl() = param and
param.getType().getUnderlyingType().getName() = "String"
)
}

private predicate isFixedAes128Length(Expr length) {
exists(DeclRefExpr ref, VarDecl lengthVar, ApplyExpr initializer, DeclRefExpr constant |
length = ref and
ref.getDecl() = lengthVar and
initializer = lengthVar.getParentInitializer() and
initializer.getAnArgument().getExpr() = constant and
constant.getDecl().(VarDecl).getName() = "kCCKeySizeAES128"
)
or
length.(DeclRefExpr).getDecl().(VarDecl).getName() = "kCCKeySizeAES128"
}

private predicate isKeyPointerForData(Expr keyPointer, Expr dataExpr) {
exists(DeclRefExpr keyRef, ClosureExpr closure, ApplyExpr withUnsafeBytes |
keyPointer = keyRef and
keyRef.getDecl() = closure.getParam(0) and
keyRef.getEnclosingCallable() = closure and
withUnsafeBytes.getStaticTarget().getName() = "withUnsafeBytes(_:)" and
withUnsafeBytes.getQualifier() = dataExpr and
withUnsafeBytes.getAnArgument().getExpr() = closure
)
or
exists(MemberRefExpr bytes, ExplicitCastExpr cast |
keyPointer = bytes and
bytes.getMember().(VarDecl).getName() = "bytes" and
bytes.getBase() = cast and
cast.getType().getUnderlyingType().getName() = "NSData" and
cast.getSubExpr() = dataExpr
)
}

private predicate validatesKeyLength(Expr cond, Expr dataExpr, boolean branch) {
exists(BinaryExpr cmp, MemberRefExpr countRef, Expr bound |
cond = cmp and
countRef = cmp.getLeftOperand() and
countRef.getMember().(VarDecl).getName() = "count" and
exists(DeclRefExpr checkedDataRef, DeclRefExpr guardedDataRef |
dataExpr = checkedDataRef and
countRef.getBase() = guardedDataRef and
checkedDataRef.getDecl() = guardedDataRef.getDecl()
) and
bound = cmp.getRightOperand() and
(
cmp.getStaticTarget().getShortName() = [">=", ">", "=="] and branch = true
or
cmp.getStaticTarget().getShortName() = ["<", "<="] and branch = false
) and
(
isFixedAes128Length(bound)
or
bound instanceof IntegerLiteralExpr and bound.toString() = "16"
)
)
}

private predicate hasKeyLengthGuard(CallExpr call, Expr dataExpr) {
exists(ConditionBlock cb, ExprCfgNode condNode, Expr cond, ExprCfgNode callNode, boolean branch |
validatesKeyLength(cond, dataExpr, branch) and
condNode.getExpr() = cond and
cb.getLastNode() = condNode and
callNode.getExpr() = call and
cb.edgeDominates(callNode.getBasicBlock(), any(BooleanSuccessor s | s.getValue() = branch))
)
}

from CallExpr call, Expr dataExpr
where
call.getStaticTarget().(Function).getShortName() = "CCCrypt" and
isFixedAes128Length(call.getArgument(4).getExpr()) and
isCallerSuppliedKey(dataExpr) and
isKeyPointerForData(call.getArgument(3).getExpr(), dataExpr) and
not hasKeyLengthGuard(call, dataExpr)
select call, "This caller-supplied key buffer may be shorter than the fixed AES-128 key length."
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Unsafe pointer access with user-controlled offset

Swift's unsafe pointer types (`UnsafePointer`, `UnsafeMutablePointer`, `UnsafeRawPointer`, `UnsafeMutableRawPointer` and their buffer counterparts) do not check that an offset, index or length stays inside the memory region they point to. Release builds also skip the debug-only checks on buffer pointer subscripts.

If a value from an untrusted source is used for pointer arithmetic, as a subscript index, as a byte offset, or as the byte count for an API that reads from a raw pointer, and the code doesn't check it against both bounds of the buffer, an attacker can read or write memory outside the buffer. This can disclose sensitive memory, corrupt data or crash the application. Negative offsets are dangerous too, because Swift's `Int` is signed: they reach memory before the start of the buffer.

## Recommendation

Avoid unsafe pointers where possible. Use safe collection APIs such as `Data.subdata(in:)`, `Array` slicing or `dropFirst(_:)`, which check their bounds.

If you must use unsafe pointers, check every untrusted offset, index or length against both the lower bound (usually `0`) and the upper bound (the size of the buffer) before you use it.

## Example

In the following example, a deep-link handler reads an `offset` query parameter from the URL and uses it directly in pointer arithmetic and to compute a byte count. A negative offset reads memory before the decoded data, and an offset larger than the data produces an invalid count:

```swift
func handleSave(_ url: URL) {
if let dataParam = getQueryParameter(url, "data"),
var data = Data(base64Encoded: dataParam),
let offsetParam = getQueryParameter(url, "offset"),
let offset = Int(offsetParam) {
let arr = [UInt8](data)
// BAD: `offset` is not checked against the bounds of `data`.
data = Data(bytes: &data + offset, count: arr.count - offset)
}
}
```

The fix is to check that the offset is inside the buffer before using it, or to use a bounds-checked API:

```swift
func handleSave(_ url: URL) {
if let dataParam = getQueryParameter(url, "data"),
let data = Data(base64Encoded: dataParam),
let offsetParam = getQueryParameter(url, "offset"),
let offset = Int(offsetParam),
offset >= 0, offset <= data.count {
// GOOD: `offset` is checked against both bounds, and `subdata(in:)` is bounds-checked.
let trimmed = data.subdata(in: offset..<data.count)
}
}
```

## References

- Apple Developer Documentation: [UnsafePointer](https://developer.apple.com/documentation/swift/unsafepointer).
- Apple Developer Documentation: [UnsafeRawPointer](https://developer.apple.com/documentation/swift/unsaferawpointer).
- Common Weakness Enumeration: [CWE-125](https://cwe.mitre.org/data/definitions/125.html).
- Common Weakness Enumeration: [CWE-787](https://cwe.mitre.org/data/definitions/787.html).
- Common Weakness Enumeration: [CWE-823](https://cwe.mitre.org/data/definitions/823.html).
Loading
Loading