From 6fe0b1c28e9b356fd215800e09fb5c83809e20d9 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:42:48 +0000 Subject: [PATCH 1/5] Initial plan From ec804744085859c34e1b02c4b69408c57a43ccad Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 31 Oct 2026 05:22:30 +0000 Subject: [PATCH 2/5] Add swift/custom/static-initialization-vector-extended for CommonCrypto, nil and default-parameter IVs Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../StaticInitializationVectorExtended.md | 57 +++++ .../StaticInitializationVectorExtended.ql | 25 +++ .../StaticInitializationVectorExtended.qll | 194 ++++++++++++++++++ ...1-static-initialization-vector-extended.md | 5 + languages/swift/custom/src/qlpack.yml | 5 + ...taticInitializationVectorExtended.expected | 33 +++ .../StaticInitializationVectorExtended.qlref | 2 + .../test.swift | 181 ++++++++++++++++ languages/swift/custom/test/qlpack.yml | 5 + 9 files changed, 507 insertions(+) create mode 100644 languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.md create mode 100644 languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.ql create mode 100644 languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll create mode 100644 languages/swift/custom/src/change-notes/2026-10-31-static-initialization-vector-extended.md create mode 100644 languages/swift/custom/src/qlpack.yml create mode 100644 languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.expected create mode 100644 languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qlref create mode 100644 languages/swift/custom/test/StaticInitializationVectorExtended/test.swift create mode 100644 languages/swift/custom/test/qlpack.yml diff --git a/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.md b/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.md new file mode 100644 index 00000000..2a32fb35 --- /dev/null +++ b/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.md @@ -0,0 +1,57 @@ +# Static initialization vector for encryption (extended) + +When you encrypt data with a block cipher mode such as CBC, the initialization vector (IV) must be unique and unpredictable for each encryption. If the IV is a constant, encrypting the same plaintext with the same key always gives the same ciphertext, and an attacker can tell when two messages share a prefix. + +The standard `swift/static-initialization-vector` query does not report the following cases, so this query reports them: + +- A constant IV passed to the CommonCrypto C API: `CCCrypt`, `CCCryptorCreate`, `CCCryptorCreateWithMode` or `CCCryptorReset`. +- A `nil` IV passed to one of these functions. CommonCrypto then uses an IV of all zero bytes, which is also a constant. +- An IV that comes from the default value of a parameter, for example `func encrypt(..., iv: Data = ...)`. Every caller that omits the argument uses the same IV. This query reports the call that omits the argument, wherever the IV reaches a sink. + +Calls that use ECB mode (`kCCOptionECBMode` or `kCCModeECB`) or the RC4 stream cipher (`kCCAlgorithmRC4` or `kCCModeRC4`) are not reported, because they do not use an IV. ECB and RC4 are weaknesses of their own. + +## Recommendation + +Generate a new random IV for every encryption, for example with `SecRandomCopyBytes`, and store or send it together with the ciphertext. Do not pass `nil` as the IV, and do not give an IV parameter a default value. If you can, use an authenticated encryption API such as CryptoKit's `AES.GCM`, which generates the nonce for you. + +## Example + +The following code passes `nil` as the IV, so CommonCrypto uses an IV of all zero bytes: + +```swift +CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), + keyBytes, keyLength, + nil, // BAD: all-zero IV + dataBytes, dataLength, cryptBytes, cryptLength, &numBytesEncrypted) +``` + +The following code gives the IV parameter a constant default value, so every call that omits `ivData` uses the same IV: + +```swift +extension Data { + func aes(keyData: Data, ivData: Data = "abcdefghijklmnop".data(using: .utf8)!) -> Data { + // ... passes ivData to CCCrypt ... + } +} + +let ciphertext = plaintext.aes(keyData: key) // BAD: uses the default IV +``` + +Instead, generate a random IV for each encryption: + +```swift +var iv = [UInt8](repeating: 0, count: kCCBlockSizeAES128) +guard SecRandomCopyBytes(kSecRandomDefault, iv.count, &iv) == errSecSuccess else { return nil } +let ciphertext = plaintext.aes(keyData: key, ivData: Data(iv)) // GOOD +``` + +## Limitations + +The CodeQL Swift extractor does not record the default value of a parameter, so the query cannot tell whether a default IV is a constant or is generated at random. A default value such as `iv: Data = randomIV()` is reported too. + +## References + +- Wikipedia: [Initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). +- Apple Developer Documentation: [SecRandomCopyBytes(_:_:\_:)](https://developer.apple.com/documentation/security/1399291-secrandomcopybytes). +- Common Weakness Enumeration: [CWE-329](https://cwe.mitre.org/data/definitions/329.html). +- Common Weakness Enumeration: [CWE-1204](https://cwe.mitre.org/data/definitions/1204.html). diff --git a/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.ql b/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.ql new file mode 100644 index 00000000..30f4361b --- /dev/null +++ b/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.ql @@ -0,0 +1,25 @@ +/** + * @name Static initialization vector for encryption (extended) + * @description Using a static initialization vector (IV) for encryption is not secure. This + * extends `swift/static-initialization-vector` with CommonCrypto IV arguments, + * `nil` IVs (which CommonCrypto replaces with all zero bytes) and IVs that come + * from a default parameter value. + * @kind path-problem + * @problem.severity error + * @security-severity 7.5 + * @precision medium + * @id swift/custom/static-initialization-vector-extended + * @tags security + * external/cwe/cwe-329 + * external/cwe/cwe-1204 + */ + +import swift +import StaticInitializationVectorExtended +import StaticInitializationVectorExtendedFlow::PathGraph + +from + StaticInitializationVectorExtendedFlow::PathNode sourceNode, + StaticInitializationVectorExtendedFlow::PathNode sinkNode, string message +where staticInitializationVectorExtended(sourceNode, sinkNode, message) +select sinkNode.getNode(), sourceNode, sinkNode, message diff --git a/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll b/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll new file mode 100644 index 00000000..7076cd47 --- /dev/null +++ b/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll @@ -0,0 +1,194 @@ +/** + * Provides a taint-tracking configuration for finding static initialization + * vectors (IVs) that the standard `swift/static-initialization-vector` query + * does not report: + * + * - IVs passed to the CommonCrypto C API (`CCCrypt`, `CCCryptorCreate`, + * `CCCryptorCreateWithMode` and `CCCryptorReset`), which the standard query + * does not model as sinks. + * - `nil` IVs passed to CommonCrypto, which CommonCrypto replaces with an + * all-zero IV. + * - IVs that come from the default value of a parameter, which is used + * whenever a caller omits the argument. + */ + +import swift +import codeql.swift.dataflow.DataFlow +import codeql.swift.dataflow.TaintTracking +import codeql.swift.security.StaticInitializationVectorQuery +private import codeql.swift.generated.ParentChild + +/** + * Holds if `call` is a call to the CommonCrypto function `name`. + */ +private predicate isCommonCryptoCall(CallExpr call, string name) { + call.getStaticTarget().(Function).getShortName() = name and + name = ["CCCrypt", "CCCryptorCreate", "CCCryptorCreateWithMode", "CCCryptorReset"] +} + +/** + * Holds if `e`, or an expression whose value flows to `e`, refers to a + * declaration named `name`. + */ +bindingset[name] +private predicate refersTo(Expr e, string name) { + exists(Expr src, DeclRefExpr ref | + DataFlow::localExprFlow(src, e) and + ref.getDecl().(VarDecl).getName() = name and + getImmediateParent*(ref) = src + ) +} + +/** + * Holds if `call` is a CommonCrypto call that ignores the IV, because it uses + * ECB mode or the RC4 stream cipher. + */ +private predicate ignoresInitializationVector(CallExpr call) { + isCommonCryptoCall(call, ["CCCrypt", "CCCryptorCreate"]) and + ( + refersTo(call.getArgument(1).getExpr(), "kCCAlgorithmRC4") or + refersTo(call.getArgument(2).getExpr(), "kCCOptionECBMode") + ) + or + isCommonCryptoCall(call, "CCCryptorCreateWithMode") and + ( + refersTo(call.getArgument(1).getExpr(), ["kCCModeECB", "kCCModeRC4"]) or + refersTo(call.getArgument(2).getExpr(), "kCCAlgorithmRC4") + ) +} + +/** + * An IV argument of a CommonCrypto function. A `nil` IV is replaced by an + * all-zero IV. + */ +class CommonCryptoInitializationVectorSink extends StaticInitializationVectorSink { + CommonCryptoInitializationVectorSink() { + exists(CallExpr call, string name, int ivIndex | + isCommonCryptoCall(call, name) and + ( + name = ["CCCrypt", "CCCryptorCreate"] and ivIndex = 5 + or + name = "CCCryptorCreateWithMode" and ivIndex = 4 + or + name = "CCCryptorReset" and ivIndex = 1 + ) and + call.getArgument(ivIndex).getExpr() = this.asExpr() and + not ignoresInitializationVector(call) + ) + } +} + +/** + * A step from the receiver of `withUnsafeBytes` or `withUnsafeMutableBytes` + * to the pointer parameter of the closure passed to it. This covers the + * deprecated generic `Data.withUnsafeBytes` overloads that pass an + * `UnsafePointer`, which is the usual way to pass a `Data` IV + * to CommonCrypto. + */ +private class WithUnsafeBytesStep extends StaticInitializationVectorAdditionalFlowStep { + override predicate step(DataFlow::Node nodeFrom, DataFlow::Node nodeTo) { + exists(CallExpr call, ClosureExpr closure | + call.getStaticTarget().(Function).getShortName() = + ["withUnsafeBytes", "withUnsafeMutableBytes"] and + call.getQualifier() = nodeFrom.asExpr() and + closure = call.getArgument(0).getExpr() and + nodeTo.asParameter() = closure.getParam(0) + ) + } +} + +/** + * A step from a (non-`inout`) parameter to a read of that parameter inside a + * nested closure. CommonCrypto calls are usually nested in several closures + * passed to library methods such as `withUnsafeBytes`, which have no body in + * the database, so the dataflow library cannot see these closures being + * called and does not track captured values into them. Parameters cannot be + * reassigned, so the step is safe regardless of when the closure runs. + */ +private class CapturedParameterStep extends StaticInitializationVectorAdditionalFlowStep { + override predicate step(DataFlow::Node nodeFrom, DataFlow::Node nodeTo) { + exists(Callable c, ParamDecl p, DeclRefExpr read | + p = c.getAParam() and + not p.isInout() and + nodeFrom.asParameter() = p and + read.getDecl() = p and + read.getEnclosingCallable() instanceof ClosureExpr and + read.getEnclosingCallable() != c and + nodeTo.asExpr() = read + ) + } +} + +/** + * An expression that is a static IV for this query: a constant + * array, string or number (as in the standard query), a `nil` literal, or a + * default argument value that a caller does not override. + */ +class ExtendedStaticInitializationVectorSource extends Expr { + ExtendedStaticInitializationVectorSource() { + this instanceof StaticInitializationVectorSource + or + this instanceof NilLiteralExpr + or + this instanceof DefaultArgumentExpr and + not this.(DefaultArgumentExpr).hasCallerSideDefault() + } +} + +/** + * A taint-tracking configuration from static IVs (including `nil` and + * default argument values) to expressions that use them as an IV. + */ +module StaticInitializationVectorExtendedConfig implements DataFlow::ConfigSig { + predicate isSource(DataFlow::Node node) { + node.asExpr() instanceof ExtendedStaticInitializationVectorSource + } + + predicate isSink(DataFlow::Node node) { node instanceof StaticInitializationVectorSink } + + predicate isBarrier(DataFlow::Node node) { node instanceof StaticInitializationVectorBarrier } + + predicate isBarrierIn(DataFlow::Node node) { + // make sources barriers so that we only report the closest instance + isSource(node) + } + + predicate isAdditionalFlowStep(DataFlow::Node nodeFrom, DataFlow::Node nodeTo) { + any(StaticInitializationVectorAdditionalFlowStep s).step(nodeFrom, nodeTo) + } +} + +/** Taint flow from static IVs to expressions that use them as an IV. */ +module StaticInitializationVectorExtendedFlow = + TaintTracking::Global; + +/** + * Holds if a static IV `source` flows to `sink` and the result is not + * already reported by the standard `swift/static-initialization-vector` + * query. `message` describes the result. + */ +predicate staticInitializationVectorExtended( + StaticInitializationVectorExtendedFlow::PathNode source, + StaticInitializationVectorExtendedFlow::PathNode sink, string message +) { + StaticInitializationVectorExtendedFlow::flowPath(source, sink) and + exists(Expr src | src = source.getNode().asExpr() | + // `nil` means "all zeros" only for CommonCrypto; other libraries (for + // example RNCryptor) generate a random IV instead. + src instanceof NilLiteralExpr and + sink.getNode() instanceof CommonCryptoInitializationVectorSink and + message = "A nil initialization vector (all zero bytes) is used for encryption." + or + src instanceof DefaultArgumentExpr and + message = + "The default value of parameter '" + src.(DefaultArgumentExpr).getParamDecl().getName() + + "' is used as an initialization vector for encryption." + or + // the standard query already reports static values that reach its own sinks + src instanceof StaticInitializationVectorSource and + sink.getNode() instanceof CommonCryptoInitializationVectorSink and + message = + "The static value '" + src.toString() + + "' is used as an initialization vector for encryption." + ) +} diff --git a/languages/swift/custom/src/change-notes/2026-10-31-static-initialization-vector-extended.md b/languages/swift/custom/src/change-notes/2026-10-31-static-initialization-vector-extended.md new file mode 100644 index 00000000..db5d5c91 --- /dev/null +++ b/languages/swift/custom/src/change-notes/2026-10-31-static-initialization-vector-extended.md @@ -0,0 +1,5 @@ +--- +category: newQuery +--- + +- Added a custom `swift/custom/static-initialization-vector-extended` query that extends `swift/static-initialization-vector`. It reports constant IVs passed to the CommonCrypto functions `CCCrypt`, `CCCryptorCreate`, `CCCryptorCreateWithMode` and `CCCryptorReset`, `nil` IVs passed to these functions (CommonCrypto then uses an all-zero IV), and IVs that come from a default parameter value. Calls in ECB mode or with the RC4 stream cipher, which ignore the IV, are not reported. Results that the standard query already reports are not repeated. 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/StaticInitializationVectorExtended/StaticInitializationVectorExtended.expected b/languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.expected new file mode 100644 index 00000000..7b185ac5 --- /dev/null +++ b/languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.expected @@ -0,0 +1,33 @@ +#select +| test.swift:78:101:78:101 | nil | test.swift:78:101:78:101 | nil | test.swift:78:101:78:101 | nil | A nil initialization vector (all zero bytes) is used for encryption. | +| test.swift:103:99:103:99 | ivBytes | test.swift:134:18:134:18 | default ivData | test.swift:103:99:103:99 | ivBytes | The default value of parameter 'ivData' is used as an initialization vector for encryption. | +| test.swift:149:119:149:119 | staticIv | test.swift:148:26:148:79 | [...] | test.swift:149:119:149:119 | staticIv | The static value '[...]' is used as an initialization vector for encryption. | +| test.swift:150:119:150:119 | 0123456789abcdef | test.swift:150:119:150:119 | 0123456789abcdef | test.swift:150:119:150:119 | 0123456789abcdef | The static value '0123456789abcdef' is used as an initialization vector for encryption. | +| test.swift:151:127:151:127 | staticIv | test.swift:148:26:148:79 | [...] | test.swift:151:127:151:127 | staticIv | The static value '[...]' is used as an initialization vector for encryption. | +| test.swift:154:127:154:127 | nil | test.swift:154:127:154:127 | nil | test.swift:154:127:154:127 | nil | A nil initialization vector (all zero bytes) is used for encryption. | +| test.swift:155:132:155:132 | nil | test.swift:155:132:155:132 | nil | test.swift:155:132:155:132 | nil | A nil initialization vector (all zero bytes) is used for encryption. | +| test.swift:156:30:156:30 | nil | test.swift:156:30:156:30 | nil | test.swift:156:30:156:30 | nil | A nil initialization vector (all zero bytes) is used for encryption. | +edges +| test.swift:91:55:91:171 | ivData | test.swift:101:5:101:5 | ivData | provenance | Config | +| test.swift:101:5:101:5 | ivData | test.swift:101:30:101:30 | ivBytes | provenance | Config | +| test.swift:101:30:101:30 | ivBytes | test.swift:103:99:103:99 | ivBytes | provenance | Config | +| test.swift:134:18:134:18 | default ivData | test.swift:91:55:91:171 | ivData | provenance | | +| test.swift:148:26:148:79 | [...] | test.swift:149:119:149:119 | staticIv | provenance | | +| test.swift:148:26:148:79 | [...] | test.swift:151:127:151:127 | staticIv | provenance | | +nodes +| test.swift:78:101:78:101 | nil | semmle.label | nil | +| test.swift:91:55:91:171 | ivData | semmle.label | ivData | +| test.swift:101:5:101:5 | ivData | semmle.label | ivData | +| test.swift:101:30:101:30 | ivBytes | semmle.label | ivBytes | +| test.swift:103:99:103:99 | ivBytes | semmle.label | ivBytes | +| test.swift:134:18:134:18 | default ivData | semmle.label | default ivData | +| test.swift:148:26:148:79 | [...] | semmle.label | [...] | +| test.swift:149:119:149:119 | staticIv | semmle.label | staticIv | +| test.swift:150:119:150:119 | 0123456789abcdef | semmle.label | 0123456789abcdef | +| test.swift:151:127:151:127 | staticIv | semmle.label | staticIv | +| test.swift:154:127:154:127 | nil | semmle.label | nil | +| test.swift:155:132:155:132 | nil | semmle.label | nil | +| test.swift:156:30:156:30 | nil | semmle.label | nil | +| test.swift:177:91:177:91 | nil | semmle.label | nil | +| test.swift:180:14:180:67 | [...] | semmle.label | [...] | +subpaths diff --git a/languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qlref b/languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qlref new file mode 100644 index 00000000..abb6e9b2 --- /dev/null +++ b/languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qlref @@ -0,0 +1,2 @@ +query: StaticInitializationVectorExtended/StaticInitializationVectorExtended.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/swift/custom/test/StaticInitializationVectorExtended/test.swift b/languages/swift/custom/test/StaticInitializationVectorExtended/test.swift new file mode 100644 index 00000000..d8594301 --- /dev/null +++ b/languages/swift/custom/test/StaticInitializationVectorExtended/test.swift @@ -0,0 +1,181 @@ +// --- stubs --- + +typealias CCCryptorStatus = Int32 +typealias CCOperation = UInt32 +typealias CCAlgorithm = UInt32 +typealias CCOptions = UInt32 +typealias CCMode = UInt32 +typealias CCPadding = UInt32 +typealias CCModeOptions = UInt32 +typealias CCCryptorRef = OpaquePointer + +let kCCSuccess = 0 +let kCCEncrypt = 0 +let kCCDecrypt = 1 +let kCCAlgorithmAES = 0 +let kCCAlgorithmAES128 = 0 +let kCCAlgorithmRC4 = 4 +let kCCOptionPKCS7Padding = 1 +let kCCOptionECBMode = 2 +let kCCModeECB = 1 +let kCCModeCBC = 2 +let kCCModeRC4 = 9 +let ccPKCS7Padding = 1 +let kCCKeySizeAES128 = 16 +let kCCBlockSizeAES128 = 16 + +func CCCrypt(_ op: CCOperation, _ alg: CCAlgorithm, _ options: CCOptions, _ key: UnsafeRawPointer!, _ keyLength: Int, _ iv: UnsafeRawPointer!, _ dataIn: UnsafeRawPointer!, _ dataInLength: Int, _ dataOut: UnsafeMutableRawPointer!, _ dataOutAvailable: Int, _ dataOutMoved: UnsafeMutablePointer!) -> CCCryptorStatus { return 0 } + +func CCCryptorCreate(_ op: CCOperation, _ alg: CCAlgorithm, _ options: CCOptions, _ key: UnsafeRawPointer!, _ keyLength: Int, _ iv: UnsafeRawPointer!, _ cryptorRef: UnsafeMutablePointer!) -> CCCryptorStatus { return 0 } + +func CCCryptorCreateWithMode(_ op: CCOperation, _ mode: CCMode, _ alg: CCAlgorithm, _ padding: CCPadding, _ iv: UnsafeRawPointer!, _ key: UnsafeRawPointer!, _ keyLength: Int, _ tweak: UnsafeRawPointer!, _ tweakLength: Int, _ numRounds: Int32, _ options: CCModeOptions, _ cryptorRef: UnsafeMutablePointer!) -> CCCryptorStatus { return 0 } + +func CCCryptorReset(_ cryptorRef: CCCryptorRef!, _ iv: UnsafeRawPointer!) -> CCCryptorStatus { return 0 } + +struct Data { + init(count: Int) { } + init(_ elements: [UInt8]) { } + + var count: Int { get { return 0 } } + + // Like the Foundation methods, these stubs do not visibly call `body`. + func withUnsafeBytes(_ body: (UnsafePointer) throws -> ResultType) rethrows -> ResultType { + fatalError() + } + + mutating func withUnsafeMutableBytes(_ body: (UnsafeMutablePointer) throws -> ResultType) rethrows -> ResultType { + fatalError() + } +} + +struct CBC { + init(iv: Array) { } +} + +class RNCryptor { } + +class RNEncryptor : RNCryptor { + func encryptData(_ thePlaintext: Data?, with theSettings: Int, encryptionKey anEncryptionKey: Data?, hmacKey anHMACKey: Data?, iv anIV: Data?) throws -> Data { return Data(count: 0) } +} + +func getRandomArray() -> [UInt8] { + (0..<16).map({ _ in UInt8.random(in: 0...UInt8.max) }) +} + +// --- tests --- + +// Reduced from iGoat-Swift `WebkitCacheExerciseVC.aesCBCDecrypt(data:keyData:)`. +func aesCBCDecrypt(data: Data, keyData: Data) -> Data? { + let keyLength = keyData.count + let clearLength = 500 + var clearData = Data(count: clearLength) + var numBytesDecrypted = 0 + let options = CCOptions(kCCOptionPKCS7Padding) + + let cryptStatus = clearData.withUnsafeMutableBytes { cryptBytes in + data.withUnsafeBytes { dataBytes in + keyData.withUnsafeBytes { keyBytes in + CCCrypt(CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES128), options, keyBytes, keyLength, nil, dataBytes, data.count, cryptBytes, clearLength, &numBytesDecrypted) // $ Alert + } + } + } + + if Int(cryptStatus) == kCCSuccess { + return clearData + } + return nil +} + +// Reduced from iGoat-Swift `Data.aes(operation:keyData:ivData:)`. +extension Data { + func aes(operation: Int = kCCEncrypt, keyData: Data, ivData: Data = Data([0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70])) -> Data { + let dataLength = self.count + let cryptLength = dataLength + kCCBlockSizeAES128 + var cryptData = Data(count: cryptLength) + let keyLength = kCCKeySizeAES128 + let options = CCOptions(kCCOptionPKCS7Padding) + var numBytesEncrypted = 0 + + let cryptStatus = cryptData.withUnsafeMutableBytes { cryptBytes in + self.withUnsafeBytes { dataBytes in + ivData.withUnsafeBytes { ivBytes in + keyData.withUnsafeBytes { keyBytes in + CCCrypt(CCOperation(operation), CCAlgorithm(kCCAlgorithmAES), options, keyBytes, keyLength, ivBytes, dataBytes, dataLength, cryptBytes, cryptLength, &numBytesEncrypted) // $ Alert + } + } + } + } + + if Int(cryptStatus) != kCCSuccess { + return Data(count: 0) + } + return cryptData + } + + // The default IV is never used, because every caller passes its own IV. + func aesExplicitIvOnly(keyData: Data, ivData: Data = Data([0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70])) -> Data { + var cryptData = Data(count: self.count + kCCBlockSizeAES128) + var numBytesEncrypted = 0 + + _ = cryptData.withUnsafeMutableBytes { cryptBytes in + self.withUnsafeBytes { dataBytes in + ivData.withUnsafeBytes { ivBytes in + keyData.withUnsafeBytes { keyBytes in + CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), keyBytes, kCCKeySizeAES128, ivBytes, dataBytes, self.count, cryptBytes, self.count + kCCBlockSizeAES128, &numBytesEncrypted) // GOOD: the IV always comes from the caller + } + } + } + } + return cryptData + } +} + +func encryptWithDefaultIv(plain: Data, key: Data) -> Data { + return plain.aes(keyData: key) // $ Source +} + +func encryptWithRandomIv(plain: Data, key: Data) -> Data { + let iv = Data(getRandomArray()) + _ = plain.aesExplicitIvOnly(keyData: key, ivData: iv) // GOOD: random IV + return plain.aes(operation: kCCEncrypt, keyData: key, ivData: iv) // GOOD: random IV +} + +func testCommonCrypto(key: [UInt8], dataIn: [UInt8], dataOut: UnsafeMutableRawPointer) { + var moved = 0 + var cryptor: CCCryptorRef? = nil + + // static IVs + let staticIv: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] // $ Source + _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), key, key.count, staticIv, dataIn, dataIn.count, dataOut, 64, &moved) // $ Alert + _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), key, key.count, "0123456789abcdef", dataIn, dataIn.count, dataOut, 64, &moved) // $ Alert + _ = CCCryptorCreate(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), key, key.count, staticIv, &cryptor) // $ Alert + + // nil (all-zero) IVs + _ = CCCryptorCreate(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), key, key.count, nil, &cryptor) // $ Alert + _ = CCCryptorCreateWithMode(CCOperation(kCCEncrypt), CCMode(kCCModeCBC), CCAlgorithm(kCCAlgorithmAES), CCPadding(ccPKCS7Padding), nil, key, key.count, nil, 0, 0, 0, &cryptor) // $ Alert + _ = CCCryptorReset(cryptor, nil) // $ Alert + + // random IVs + let randomIv = getRandomArray() + _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), key, key.count, randomIv, dataIn, dataIn.count, dataOut, 64, &moved) // GOOD + _ = CCCryptorCreate(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), key, key.count, randomIv, &cryptor) // GOOD + _ = CCCryptorReset(cryptor, randomIv) // GOOD + + // ECB mode ignores the IV (ECB itself is a different weakness) + _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionECBMode | kCCOptionPKCS7Padding), key, key.count, nil, dataIn, dataIn.count, dataOut, 64, &moved) // GOOD + let ecbOptions = CCOptions(kCCOptionECBMode) + _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), ecbOptions, key, key.count, nil, dataIn, dataIn.count, dataOut, 64, &moved) // GOOD + _ = CCCryptorCreateWithMode(CCOperation(kCCEncrypt), CCMode(kCCModeECB), CCAlgorithm(kCCAlgorithmAES), CCPadding(ccPKCS7Padding), nil, key, key.count, nil, 0, 0, 0, &cryptor) // GOOD + + // the RC4 stream cipher ignores the IV (RC4 itself is a different weakness) + _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmRC4), 0, key, key.count, nil, dataIn, dataIn.count, dataOut, 64, &moved) // GOOD + _ = CCCryptorCreateWithMode(CCOperation(kCCEncrypt), CCMode(kCCModeRC4), CCAlgorithm(kCCAlgorithmRC4), 0, nil, key, key.count, nil, 0, 0, 0, &cryptor) // GOOD +} + +func testOtherLibraries(plain: Data, key: Data) { + // RNCryptor generates a random IV when `nil` is passed + _ = try? RNEncryptor().encryptData(plain, with: 0, encryptionKey: key, hmacKey: key, iv: nil) // GOOD + + // already reported by the standard `swift/static-initialization-vector` query + _ = CBC(iv: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) // GOOD (not duplicated) +} 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 From c8dbff386c69f04252febceb9e52ba25671eb625 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:39:50 +0000 Subject: [PATCH 3/5] Skip Swift unit tests on Linux Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .github/workflows/codeql-qlt-unit-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codeql-qlt-unit-tests.yml b/.github/workflows/codeql-qlt-unit-tests.yml index 2a8b6ef7..c62889f0 100644 --- a/.github/workflows/codeql-qlt-unit-tests.yml +++ b/.github/workflows/codeql-qlt-unit-tests.yml @@ -54,7 +54,7 @@ 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 + if [[ "$lang" == "ql" || "$lang" == "actions" || "$lang" == "swift" ]]; then echo "⚠️ qlt unit testing is not currently supported for language: $lang" continue fi From e558283043d45551d6d25c74c14b48a36d87e49e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:46:07 +0000 Subject: [PATCH 4/5] Limit Swift mode checks to value-preserving paths Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../StaticInitializationVectorExtended.qll | 48 +++++++++++++++++-- ...taticInitializationVectorExtended.expected | 2 + .../test.swift | 6 +++ 3 files changed, 51 insertions(+), 5 deletions(-) diff --git a/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll b/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll index 7076cd47..11b1cf07 100644 --- a/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll +++ b/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll @@ -27,15 +27,53 @@ private predicate isCommonCryptoCall(CallExpr call, string name) { } /** - * Holds if `e`, or an expression whose value flows to `e`, refers to a - * declaration named `name`. + * Holds if `e` refers to a declaration named `name` through expressions that + * preserve its value. */ bindingset[name] private predicate refersTo(Expr e, string name) { - exists(Expr src, DeclRefExpr ref | - DataFlow::localExprFlow(src, e) and + exists(DeclRefExpr ref | ref.getDecl().(VarDecl).getName() = name and - getImmediateParent*(ref) = src + valuePreservingReference(e, ref) + ) +} + +/** + * Holds if `e` is `ref`, or is an expression that preserves the value of `ref`. + */ +private predicate valuePreservingReference(Expr e, DeclRefExpr ref) { + e = ref + or + exists(ParenExpr parens | + e = parens and + valuePreservingReference(parens.getImmediateSubExpr(), ref) + ) + or + exists(CallExpr conversion | + e = conversion and + conversion.getStaticTarget().(Initializer).getEnclosingDecl().asNominalTypeDecl().getName() = + ["CCOptions", "UInt32"] and + valuePreservingReference(conversion.getArgument(0).getExpr(), ref) + ) + or + exists(OrBitwiseExpr bitwiseOr | + e = bitwiseOr and + valuePreservingReference(bitwiseOr.getAnOperand(), ref) + ) + or + exists(DeclRefExpr localRef, VarDecl localVariable, Expr initializer | + e = localRef and + localRef.getDecl() = localVariable and + initializer = localVariable.getParentInitializer() and + DataFlow::localExprFlow(initializer, localRef) and + valuePreservingReference(initializer, ref) + ) + or + exists(DeclRefExpr localRef, AssignExpr assignment | + e = localRef and + assignment.getDest() = localRef and + DataFlow::localExprFlow(assignment.getSource(), localRef) and + valuePreservingReference(assignment.getSource(), ref) ) } diff --git a/languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.expected b/languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.expected index 7b185ac5..29f3e572 100644 --- a/languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.expected +++ b/languages/swift/custom/test/StaticInitializationVectorExtended/StaticInitializationVectorExtended.expected @@ -7,6 +7,8 @@ | test.swift:154:127:154:127 | nil | test.swift:154:127:154:127 | nil | test.swift:154:127:154:127 | nil | A nil initialization vector (all zero bytes) is used for encryption. | | test.swift:155:132:155:132 | nil | test.swift:155:132:155:132 | nil | test.swift:155:132:155:132 | nil | A nil initialization vector (all zero bytes) is used for encryption. | | test.swift:156:30:156:30 | nil | test.swift:156:30:156:30 | nil | test.swift:156:30:156:30 | nil | A nil initialization vector (all zero bytes) is used for encryption. | +| test.swift:171:97:171:97 | nil | test.swift:171:97:171:97 | nil | test.swift:171:97:171:97 | nil | A nil initialization vector (all zero bytes) is used for encryption. | +| test.swift:173:105:173:105 | nil | test.swift:173:105:173:105 | nil | test.swift:173:105:173:105 | nil | A nil initialization vector (all zero bytes) is used for encryption. | edges | test.swift:91:55:91:171 | ivData | test.swift:101:5:101:5 | ivData | provenance | Config | | test.swift:101:5:101:5 | ivData | test.swift:101:30:101:30 | ivBytes | provenance | Config | diff --git a/languages/swift/custom/test/StaticInitializationVectorExtended/test.swift b/languages/swift/custom/test/StaticInitializationVectorExtended/test.swift index d8594301..56018eff 100644 --- a/languages/swift/custom/test/StaticInitializationVectorExtended/test.swift +++ b/languages/swift/custom/test/StaticInitializationVectorExtended/test.swift @@ -165,6 +165,12 @@ func testCommonCrypto(key: [UInt8], dataIn: [UInt8], dataOut: UnsafeMutableRawPo _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionECBMode | kCCOptionPKCS7Padding), key, key.count, nil, dataIn, dataIn.count, dataOut, 64, &moved) // GOOD let ecbOptions = CCOptions(kCCOptionECBMode) _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), ecbOptions, key, key.count, nil, dataIn, dataIn.count, dataOut, 64, &moved) // GOOD + let wrappedEcbOptions = CCOptions(UInt32((kCCOptionECBMode)) | UInt32(kCCOptionPKCS7Padding)) + _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), wrappedEcbOptions, key, key.count, nil, dataIn, dataIn.count, dataOut, 64, &moved) // GOOD + let cbcOptions = CCOptions(kCCOptionPKCS7Padding & ~kCCOptionECBMode) + _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), cbcOptions, key, key.count, nil, dataIn, dataIn.count, dataOut, 64, &moved) // $ Alert + let conditionalOptions = CCOptions(dataIn.count > 0 ? kCCOptionECBMode : kCCOptionPKCS7Padding) + _ = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), conditionalOptions, key, key.count, nil, dataIn, dataIn.count, dataOut, 64, &moved) // $ Alert _ = CCCryptorCreateWithMode(CCOperation(kCCEncrypt), CCMode(kCCModeECB), CCAlgorithm(kCCAlgorithmAES), CCPadding(ccPKCS7Padding), nil, key, key.count, nil, 0, 0, 0, &cryptor) // GOOD // the RC4 stream cipher ignores the IV (RC4 itself is a different weakness) From 7af84594baf30a1ca27fccda44a9ae79ee2a076b Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:49:01 +0000 Subject: [PATCH 5/5] Recognize Swift integer conversion initializers Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../StaticInitializationVectorExtended.qll | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll b/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll index 11b1cf07..ce9f943d 100644 --- a/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll +++ b/languages/swift/custom/src/StaticInitializationVectorExtended/StaticInitializationVectorExtended.qll @@ -51,8 +51,8 @@ private predicate valuePreservingReference(Expr e, DeclRefExpr ref) { or exists(CallExpr conversion | e = conversion and - conversion.getStaticTarget().(Initializer).getEnclosingDecl().asNominalTypeDecl().getName() = - ["CCOptions", "UInt32"] and + conversion.getStaticTarget() instanceof Initializer and + conversion.getType().getName() = ["CCOptions", "UInt32"] and valuePreservingReference(conversion.getArgument(0).getExpr(), ref) ) or