diff --git a/.github/workflows/codeql-qlt-unit-tests.yml b/.github/workflows/codeql-qlt-unit-tests.yml index 2a8b6ef7..4b328f2c 100644 --- a/.github/workflows/codeql-qlt-unit-tests.yml +++ b/.github/workflows/codeql-qlt-unit-tests.yml @@ -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 diff --git a/languages/swift/custom/src/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.md b/languages/swift/custom/src/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.md new file mode 100644 index 00000000..7fc9110c --- /dev/null +++ b/languages/swift/custom/src/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.md @@ -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). diff --git a/languages/swift/custom/src/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.ql b/languages/swift/custom/src/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.ql new file mode 100644 index 00000000..ed1f33d6 --- /dev/null +++ b/languages/swift/custom/src/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.ql @@ -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." diff --git a/languages/swift/custom/src/UntrustedPointerOffset/UntrustedPointerOffset.md b/languages/swift/custom/src/UntrustedPointerOffset/UntrustedPointerOffset.md new file mode 100644 index 00000000..7d8b0b52 --- /dev/null +++ b/languages/swift/custom/src/UntrustedPointerOffset/UntrustedPointerOffset.md @@ -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..", ">="] and + lesser = cmp.getRightOperand() and + greater = cmp.getLeftOperand() + ) and + ( + lesser = checkedRef and checkedRef.getDecl() = v and isUpperIfTrue = true + or + greater = checkedRef and checkedRef.getDecl() = v and isUpperIfTrue = false + ) and + ( + branch = true and isUpper = isUpperIfTrue + or + branch = false and isUpper = isUpperIfTrue.booleanNot() + ) + ) + or + // Bounded and partial range checks, such as `(0..; + +from + UntrustedPointerOffsetFlow::PathNode source, UntrustedPointerOffsetFlow::PathNode sink, + UnsafePointerOffsetSink sinkNode +where + UntrustedPointerOffsetFlow::flowPath(source, sink) and + sinkNode = sink.getNode() +select sink.getNode(), source, sink, + "This value is used as an unchecked " + sinkNode.getKind() + " and depends on a $@.", + source.getNode(), "user-provided value" 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/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.qlref b/languages/swift/custom/test/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.qlref new file mode 100644 index 00000000..43ff8872 --- /dev/null +++ b/languages/swift/custom/test/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.qlref @@ -0,0 +1,2 @@ +query: UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/swift/custom/test/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.swift b/languages/swift/custom/test/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.swift new file mode 100644 index 00000000..02667058 --- /dev/null +++ b/languages/swift/custom/test/UntrustedCryptoKeyLength/UntrustedCryptoKeyLength.swift @@ -0,0 +1,54 @@ +import Foundation + +let kCCKeySizeAES128 = 16 + +func CCCrypt( + _ operation: Int, + _ algorithm: Int, + _ options: Int, + _ key: Any?, + _ keyLength: size_t, + _ iv: Any?, + _ input: Any?, + _ inputLength: Int, + _ output: Any?, + _ outputLength: Int, + _ outputMoved: Any? +) -> Int { + return 0 +} + +func encryptData(keyData: Data, ivData: Data, input: Data, output: Data) { + let keyLength = size_t(kCCKeySizeAES128) + _ = keyData.withUnsafeBytes { keyBytes in + CCCrypt(0, 0, 0, keyBytes, keyLength, ivData, input, input.count, output, output.count, nil) // $ Alert + } +} + +func encryptString(key: String, iv: String, input: Data, output: Data) { + guard let keyData = key.data(using: .utf8) else { return } + let keyLength = size_t(kCCKeySizeAES128) + _ = CCCrypt(0, 0, 0, (keyData as NSData).bytes, keyLength, iv, input, input.count, output, output.count, nil) // $ Alert +} + +func encryptCheckedKey(keyData: Data, ivData: Data, input: Data, output: Data) { + guard keyData.count >= kCCKeySizeAES128 else { return } + let keyLength = size_t(kCCKeySizeAES128) + _ = keyData.withUnsafeBytes { keyBytes in + CCCrypt(0, 0, 0, keyBytes, keyLength, ivData, input, input.count, output, output.count, nil) + } +} + +func encryptWithBufferLength(keyData: Data, ivData: Data, input: Data, output: Data) { + _ = keyData.withUnsafeBytes { keyBytes in + CCCrypt(0, 0, 0, keyBytes, size_t(keyData.count), ivData, input, input.count, output, output.count, nil) + } +} + +func encryptKnownKey(ivData: Data, input: Data, output: Data) { + let keyData = Data(repeating: 0, count: kCCKeySizeAES128) + let keyLength = size_t(kCCKeySizeAES128) + _ = keyData.withUnsafeBytes { keyBytes in + CCCrypt(0, 0, 0, keyBytes, keyLength, ivData, input, input.count, output, output.count, nil) + } +} diff --git a/languages/swift/custom/test/UntrustedPointerOffset/UntrustedPointerOffset.qlref b/languages/swift/custom/test/UntrustedPointerOffset/UntrustedPointerOffset.qlref new file mode 100644 index 00000000..5effd0ec --- /dev/null +++ b/languages/swift/custom/test/UntrustedPointerOffset/UntrustedPointerOffset.qlref @@ -0,0 +1,2 @@ +query: UntrustedPointerOffset/UntrustedPointerOffset.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/swift/custom/test/UntrustedPointerOffset/UntrustedPointerOffset.swift b/languages/swift/custom/test/UntrustedPointerOffset/UntrustedPointerOffset.swift new file mode 100644 index 00000000..f77ce419 --- /dev/null +++ b/languages/swift/custom/test/UntrustedPointerOffset/UntrustedPointerOffset.swift @@ -0,0 +1,198 @@ +// --- stubs --- + +class UIApplication { + struct OpenURLOptionsKey : Hashable { + static func == (lhs: OpenURLOptionsKey, rhs: OpenURLOptionsKey) -> Bool { + return true; + } + + func hash(into hasher: inout Hasher) {} + } +} + +struct URL { + init?(string: String) {} + + var lastPathComponent: 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 NSURLComponents { + init?(url: URL, resolvingAgainstBaseURL resolve: Bool) {} + + var queryItems: [URLQueryItem]? { get { return nil } } +} + +struct Data : Sequence { + init?(base64Encoded base64String: String) {} + init(bytes: UnsafeRawPointer, count: Int) {} + init(_ elements: S) where S.Element == UInt8 {} + + var count: Int { get { return 0 } } + + func makeIterator() -> IndexingIterator<[UInt8]> { return [UInt8]().makeIterator() } +} + +protocol UIApplicationDelegate { + func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool +} + +struct CustomMembership { + func contains(_ value: Int) -> Bool { return true } +} + +struct Request { + var count: Int +} + +// --- tests --- + +func getQueryParameter(_ url: URL, _ name: String) -> String? { + if let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true), let params = components.queryItems { + if let value = params.first(where: { $0.name == name })?.value { + return value + } + } + return nil +} + +class AppDelegate: UIApplicationDelegate { + func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool { // $ Source + handleSave(url) + handleOther(url) + handleSafe(url) + return true + } + + // Reduced from the "save" deep-link route of a vulnerable iOS sample app. + func handleSave(_ url: URL) { + if url.lastPathComponent == "save", + let dataParam = getQueryParameter(url, "data"), + var data = Data(base64Encoded: dataParam) { + if let offsetParam = getQueryParameter(url, "offset"), let offset = Int(offsetParam) { + let arr = [UInt8](data) + data = Data(bytes: &data + offset, count: arr.count - offset) // $ Alert + } + _ = data + } + } + + func handleOther(_ url: URL) { + let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] + guard let raw = items.first?.value, let index = Int(raw) else { return } + + let buffer = UnsafeMutablePointer.allocate(capacity: 16) + defer { buffer.deallocate() } + + _ = buffer.advanced(by: index) // $ Alert + _ = buffer[index] // $ Alert + _ = buffer - index // $ Alert + + var cursor = UnsafeRawPointer(buffer) + cursor += index // $ Alert + _ = cursor + + let bytes = [UInt8](repeating: 0, count: 16) + bytes.withUnsafeBufferPointer { ptr in + _ = ptr.baseAddress! + index // $ Alert + } + } + + func handleSafe(_ url: URL) { + let data = Data([1, 2, 3, 4]) + guard let offsetParam = getQueryParameter(url, "offset"), let offset = Int(offsetParam) else { return } + + // GOOD: offset is validated against the bounds of the buffer. + if offset >= 0 && offset < data.count { + var copy = data + _ = Data(bytes: © + offset, count: data.count - offset) + } + + // GOOD: guard statement rejects out-of-range offsets. + guard offset >= 0, offset < data.count else { return } + let buffer = UnsafeMutablePointer.allocate(capacity: 16) + defer { buffer.deallocate() } + _ = buffer.advanced(by: offset) + + // GOOD: range containment check. + let other = UnsafeMutablePointer.allocate(capacity: 16) + defer { other.deallocate() } + if let raw = getQueryParameter(url, "index"), let index = Int(raw), (0..<16).contains(index) { + _ = other[index] + } + + if let raw = getQueryParameter(url, "rangeIndex"), + let rangeIndex = Int(raw), 0..<16 ~= rangeIndex { + _ = other[rangeIndex] + } + + // GOOD: constant offset, not attacker controlled. + _ = other + 4 + _ = other.advanced(by: 8) + } + + func handleUncheckedRanges(_ url: URL) { + guard let raw = getQueryParameter(url, "index"), let index = Int(raw) else { return } + let buffer = UnsafeMutablePointer.allocate(capacity: 16) + defer { buffer.deallocate() } + + if (0...).contains(index) { + _ = buffer[index] // $ Alert + } + + if (..<16).contains(index) { + _ = buffer[index] // $ Alert + } + + if CustomMembership().contains(index) { + _ = buffer[index] // $ Alert + } + + if (0...) ~= index { + _ = buffer[index] // $ Alert + } + } + + func handleReassignedIndex(_ url: URL) { + guard let raw = getQueryParameter(url, "index"), var index = Int(raw) else { return } + guard index >= 0, index < 16 else { return } + + guard let replacement = getQueryParameter(url, "replacement"), + let replacementIndex = Int(replacement) else { return } + index = replacementIndex + + let buffer = UnsafeMutablePointer.allocate(capacity: 16) + defer { buffer.deallocate() } + _ = buffer[index] // $ Alert + } + + func handleUntrustedClampBound(_ url: URL) { + guard let raw = getQueryParameter(url, "index"), let index = Int(raw) else { return } + let buffer = UnsafeMutablePointer.allocate(capacity: 16) + defer { buffer.deallocate() } + + let notClamped = min(max(index, 0), index) + _ = buffer[notClamped] // $ Alert + + let clamped = min(max(index, 0), 15) + _ = buffer[clamped] + } + + func handleCustomSizeProperty(_ url: URL) { + guard let raw = getQueryParameter(url, "count"), let count = Int(raw) else { return } + let request = Request(count: count) + let buffer = UnsafeMutablePointer.allocate(capacity: 16) + defer { buffer.deallocate() } + _ = buffer[request.count] // $ Alert + } +} 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