Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
b13aed9
unified: Copy cleartext database query baseline
geoffw0 Nov 20, 2026
80f7c5c
unified: Collect cleartext database models
geoffw0 Nov 20, 2026
3c5d758
unified: Port cleartext database query
geoffw0 Nov 20, 2026
c2339ec
unified: Detect direct database property writes
geoffw0 Nov 20, 2026
8364fb3
Unified: Pull the tests out of the CleartextStorageDatabase subdirect…
geoffw0 Nov 20, 2026
9a321e4
Unified: Add TODOs and comments, including some comments restored fro…
geoffw0 Nov 20, 2026
f07968f
Unified: Standardize on the alert message we use for rust.
geoffw0 Nov 23, 2026
ea4ef47
Unified: Simplify barrier implementation.
geoffw0 Nov 23, 2026
c138acc
Unified: Clean up test annotations.
geoffw0 Nov 23, 2026
9800cb4
Unified: Accept consistency test results.
geoffw0 Nov 23, 2026
c272ca1
Merge branch 'main' into unifieddatabase
geoffw0 Nov 26, 2026
44236a2
Unified: Disable a few models that are causing problems right now.
geoffw0 Nov 26, 2026
f582a61
Merge branch 'main' into unifieddatabase
geoffw0 Dec 1, 2026
a60e700
Unified: Accept .expected changes following merge.
geoffw0 Dec 1, 2026
5c26559
Unified: Fix a typo in the test, so that it tests the intended thing.
geoffw0 Dec 1, 2026
d25c964
Merge branch 'main' into unifieddatabase
geoffw0 Dec 3, 2026
f9b642f
Unified: Add stub-free test cases.
geoffw0 Dec 4, 2026
f91772e
Unified: Use Copilot recommended isSubclassOf implementation.
geoffw0 Dec 4, 2026
20a654c
Unified: Convert setValue models to MaD.
geoffw0 Dec 4, 2026
264f5b8
Update unified/ql/src/queries/security/CWE-311/CleartextStorageDataba…
geoffw0 Dec 4, 2026
62f2ce4
Unified: Remove the additional flow step (that is no longer needed).
geoffw0 Dec 4, 2026
85675f6
Unified: Autoformat.
geoffw0 Dec 4, 2026
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
11 changes: 7 additions & 4 deletions unified/ql/lib/ext/database.model.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@
["", "Statement", true, "bind(_:)", "", "", "Argument[0]", "database-store", "manual"],
["", "Statement", true, "run(_:)", "", "", "Argument[0]", "database-store", "manual"],
["", "Statement", true, "scalar(_:)", "", "", "Argument[0]", "database-store", "manual"],
["", "QueryType", true, "insert(_:)", "", "", "Argument[0]", "database-store", "manual"],
//["", "QueryType", true, "insert(_:)", "", "", "Argument[0]", "database-store", "manual"],
["", "QueryType", true, "update(_:)", "", "", "Argument[0]", "database-store", "manual"],
["", "QueryType", true, "insert(_:_:)", "", "", "Argument[0,1]", "database-store", "manual"],
["", "QueryType", true, "insert(or:_:)", "", "", "Argument[0]", "database-store", "manual"],
//["", "QueryType", true, "insert(_:_:)", "", "", "Argument[0,1]", "database-store", "manual"], --- too noisy while sink matching is imprecise
//["", "QueryType", true, "insert(or:_:)", "", "", "Argument[0]", "database-store", "manual"],
["", "QueryType", true, "insertMany(_:)", "", "", "Argument[0]", "database-store", "manual"],
["", "QueryType", true, "insertMany(or:_:)", "", "", "Argument[0]", "database-store", "manual"],
["", "QueryType", true, "update(_:_:)", "", "", "Argument[0,1]", "database-store", "manual"],
Expand Down Expand Up @@ -124,7 +124,10 @@
["", "Realm.Configuration", true, "init(fileURL?:inMemoryIdentifier?:syncConfiguration?:encryptionKey?:readOnly?:schemaVersion?:migrationBlock?:deleteRealmIfMigrationNeeded?:shouldCompactOnLaunch?:objectTypes?:seedFilePath:)", "", "", "Argument[encryptionKey:]", "encryption-key", "manual"],
["", "Realm.Configuration", true, "init(fileURL?:inMemoryIdentifier?:syncConfiguration?:encryptionKey?:readOnly?:schemaVersion?:migrationBlock?:deleteRealmIfMigrationNeeded?:shouldCompactOnLaunch?:objectTypes?:seedFilePath:)", "", "", "Argument[seedFilePath:]", "path-injection", "manual"],
["", "Realm.Configuration", true, "fileURL", "", "", "PostUpdate", "path-injection", "manual"],
["", "Realm.Configuration", true, "seedFilePath", "", "", "PostUpdate", "path-injection", "manual"]
["", "Realm.Configuration", true, "seedFilePath", "", "", "PostUpdate", "path-injection", "manual"],
// Core Data
["", "NSManagedObject", true, "setValue(_:forKey:)", "", "", "Argument[0]", "database-store", "manual"],
["", "NSManagedObject", true, "setPrimitiveValue(_:forKey:)", "", "", "Argument[0]", "database-store", "manual"]
]
}
]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<!DOCTYPE qhelp PUBLIC "-//Semmle//qhelp//EN" "qhelp.dtd">
<qhelp>
<overview>

<p>Sensitive information that is stored unencrypted in a database is accessible to an attacker who gains access to that database. For example, the information could be accessed by any process or user in a rooted device, or exposed through another vulnerability.</p>

</overview>
<recommendation>

<p>Either encrypt the entire database, or ensure that each piece of sensitive information is encrypted before being stored. In general, decrypt sensitive information only at the point where it is necessary for it to be used in cleartext. Avoid storing sensitive information at all if you do not need to keep it.</p>

</recommendation>
<example>

<p>The following example shows three cases of storing information using the Core Data library. In the 'BAD' case, the data that is stored is sensitive (a credit card number) and is not encrypted. In the 'GOOD' cases, the data is either not sensitive, or is protected with encryption. When encryption is used, take care to select a secure modern encryption algorithm, and put suitable key management practices into place.</p>

<sample src="CleartextStorageDatabase.swift" />

</example>
<references>

<li>
OWASP Top 10:2021:
<a href="https://top10.owasp.org/2021/A02_2021-Cryptographic_Failures/index.html">A02:2021 - Cryptographic Failures</a>.
</li>
<li>
OWASP:
<a href="https://cheatsheetseries.owasp.org/cheatsheets/Key_Management_Cheat_Sheet.html">Key Management Cheat Sheet</a>.
</li>

</references>
</qhelp>
114 changes: 114 additions & 0 deletions unified/ql/src/queries/security/CWE-311/CleartextStorageDatabase.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* @name Cleartext storage of sensitive information in a local database
* @description Storing sensitive information in a non-encrypted
* database can expose it to an attacker.
* @kind path-problem
* @problem.severity warning
* @security-severity 7.5
* @precision high
* @id unified/swift/cleartext-storage-database
* @tags security
* external/cwe/cwe-312
*/

import unified
import codeql.unified.security.SensitiveData
private import codeql.unified.internal.typeinference.TypeInference as TypeInference

/**
* Holds if `cls` is a subclass of `baseName`, including `baseName` itself.
*/
bindingset[baseName]
private predicate isSubclassOf(ClassLikeDeclaration cls, string baseName) {
// TODO: if we want this predicate, it should probably be in a library?
// TODO: share code with `getSimpleNameFromExpr` or `getQualifiedNameFromExpr` in `LegacyMaD.qll`???
exists(ClassLikeDeclaration ancestor | ancestor = cls.getABaseClass*() |
ancestor.getName() = baseName
or
ancestor.getABaseType().getType().(Identifier).getValue() = baseName
or
ancestor.getABaseType().getType().(MemberAccessExpr).getMemberName() = baseName
)
}

/**
* Holds if `node` is a value stored through a Core Data API.
*/
private predicate coreDataSink(DataFlow::Node node) {
// any write into a class derived from `NSManagedObject` is a sink. For
// example in `coreDataObj.data = sensitive` the post-update node corresponding
// with `coreDataObj.data` is a sink.
// (ideally this would be only members with the `@NSManaged` attribute)
exists(MemberAccessExpr access |
(node.isIncomingValue(access) or node.isPostUpdate(access)) and
isSubclassOf(TypeInference::inferType(access.getBase()).asClass(), "NSManagedObject")
// TODO: original Swift had an exception for `SelfParamDecl` here.
)
}

/**
* Holds if `node` is a value assigned to a persisted Realm object.
*/
private predicate realmSink(DataFlow::Node node) {
exists(MemberAccessExpr access |
// `RealmSwiftObject`
(node.isIncomingValue(access) or node.isPostUpdate(access)) and
isSubclassOf(TypeInference::inferType(access.getBase()).asClass(), "RealmSwiftObject")
//or
// `Object`, when it is defined within `RealmSwift`.
// TODO
)
}

/**
* A taint-tracking configuration for cleartext database storage vulnerabilities.
*/
module CleartextStorageDatabaseConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node node) { node instanceof SensitiveData }
Comment thread
geoffw0 marked this conversation as resolved.
Resolved

predicate isSink(DataFlow::Node node) {
// There are relevant two sink types:
// - an `sql-injection` sink is SQL or similar query data passed to a database operation.
// - a `database-store` sink is non-query data passed to a database operation.
// Keeping them separate is useful for the SQL injection query, whereas here we just want
// both.
Models::isSink(node, ["sql-injection", "database-store"])
or
coreDataSink(node)
or
realmSink(node)
}

predicate isBarrier(DataFlow::Node node) {
// encrypted values are not cleartext.
// TODO: pull the encryption logic out to a class `EncryptedExpr` as in original Swift;
// we will certainly want this elsewhere.
exists(CallExpr call, FunctionDeclaration target, Expr argument |
target = TypeInference::resolveCallTarget(call) and
target.getName().regexpMatch("(?is).*(crypt|hash|encode|protect).*") and
Comment thread
geoffw0 marked this conversation as resolved.
Resolved
argument = call.getAnArgument().getValue() and
node.asExpr() = argument
)
or
// booleans are more likely to be settings than actual sensitive data.
TypeInference::inferType(node.asExpr()).asClass().getName() = "Bool"
// TODO: verify that the `Bool` barrier works.
// TODO: Add models-as-data barriers.
}

predicate isBarrierIn(DataFlow::Node node) { isSource(node) }

// TODO: original Swift had two cases in `allowImplicitRead` we may wish to port over.
predicate observeDiffInformedIncrementalMode() { any() }
}

module CleartextStorageDatabaseFlow = TaintTracking::Global<CleartextStorageDatabaseConfig>;

import CleartextStorageDatabaseFlow::PathGraph

from
CleartextStorageDatabaseFlow::PathNode sourceNode, CleartextStorageDatabaseFlow::PathNode sinkNode
where CleartextStorageDatabaseFlow::flowPath(sourceNode, sinkNode)
select sinkNode.getNode(), sourceNode, sinkNode,
"This database operation may read or write unencrypted sensitive data from $@.",
sourceNode.getNode(), sourceNode.getNode().toString()
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import CryptoKit

private func encrypt(_ text: String, _ encryptionKey: SymmetricKey) -> String {
let sealedBox = try! AES.GCM.seal(Data(text.utf8), using: encryptionKey)
return sealedBox.combined!.base64EncodedString()
}

func storeMyData(databaseObject: NSManagedObject, faveSong: String, creditCardNo: String, encryptionKey: SymmetricKey) {
// ...

// GOOD: not sensitive information
databaseObject.setValue(faveSong, forKey: "myFaveSong")

// BAD: sensitive information saved in cleartext
databaseObject.setValue(creditCardNo, forKey: "myCreditCardNo")

// GOOD: encrypted sensitive information saved
databaseObject.setValue(encrypt(creditCardNo, encryptionKey), forKey: "myCreditCardNo")

// ...
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
readWithoutDef
| testSwiftUI.swift:70:2:75:2 | self | testSwiftUI.swift:72:13:74:3 | Entry | 12 |
| testSwiftUI.swift:77:2:82:2 | self | testSwiftUI.swift:79:13:81:3 | Entry | 12 |
readWithoutPriorRef
| testSwiftUI.swift:70:2:75:2 | self | testSwiftUI.swift:72:13:74:3 | Entry | 12 |
| testSwiftUI.swift:77:2:82:2 | self | testSwiftUI.swift:79:13:81:3 | Entry | 12 |
Loading
Loading