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
2 changes: 1 addition & 1 deletion .github/workflows/codeql-qlt-unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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).
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
/**
* 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` refers to a declaration named `name` through expressions that
* preserve its value.
*/
bindingset[name]
private predicate refersTo(Expr e, string name) {
exists(DeclRefExpr ref |
ref.getDecl().(VarDecl).getName() = name and
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() instanceof Initializer and
conversion.getType().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)
)
}

/**
* 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<ContentType>`, 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<StaticInitializationVectorExtendedConfig>;

/**
* 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."
)
}
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions languages/swift/custom/src/qlpack.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name: languages-swift-custom-src
version: 0.0.2
library: false
dependencies:
codeql/swift-all: "*"
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#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. |
| 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 |
| 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
query: StaticInitializationVectorExtended/StaticInitializationVectorExtended.ql
postprocess: utils/test/InlineExpectationsTestQuery.ql
Loading
Loading