Skip to content

Unified: Port CleartextStorageDatabase query - #23215

Open
geoffw0 wants to merge 16 commits into
github:mainfrom
geoffw0:unifieddatabase
Open

geoffw0 wants to merge 16 commits into
github:mainfrom
geoffw0:unifieddatabase

Conversation

@geoffw0

@geoffw0 geoffw0 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Port the "Cleartext storage of sensitive information in a local database" query to unified, as unified/swift/cleartext-storage-database. Most of the work was done with Copilot / MAI Code 2 / High effort, with a skill setting expectations, plus some manual (ish) fixes afterwards.

A few thoughts:

  • the agent killed a mechanism cleanupNode + getASelectedSinkLocation from the original version, that cleaned up source locations, i.e. made the alerts a bit more presentable. I think this is no longer necessary in unified, but looking at real world results (e.g. when we have a DCA run) will confirm.
  • there are loads of test cases in this PR, though some are in fact designed for the upcoming unified/swift/cleartext-transmission query. That query is closely related to this one and the tests were in the same directory in original Swift as well. That is preserved here and I don't think it would be valuable to separate them.
  • obviously we don't find the unified/swift/cleartext-transmission test cases yet, we also don't catch large chunks of the unified/swift/cleartext-storage-database test cases either - in some cases entire files of test cases are missed. There is follow-up work to be done in these areas. We have enough to see the query working.
  • there are also a number of TODO comments in the query itself, to be addressed as follow-up.

geoffw0 and others added 9 commits November 23, 2026 14:35
Copy the original Swift query, help example, and focused query tests byte-for-byte into the unified layout. This establishes the baseline for the CleartextStorageDatabase port without changing behavior or metadata.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Inline the original Swift cleartext database flow configuration, extension classes, and CSV models into the unified query. The declarations remain unchanged for a reviewable mechanical baseline before API adaptation.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Adapt cleartext database storage tracking to unified Swift data flow, sensitive-data classification, and existing database models. Update the focused test reference and inline expectations; the compiling baseline reports 30 results with unsupported cases explicitly marked as missing.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Treat incoming values for persisted Core Data and Realm member accesses as database storage sinks. This recovers direct property-write detections from the original query and updates the generated baseline from 30 to 56 results with known false positives annotated.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ory, these tests were designed to cover two related queries.
@geoffw0 geoffw0 added no-change-note-required This PR does not need a change note Unified labels Nov 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

QHelp previews:

unified/ql/src/queries/security/CWE-311/CleartextStorageDatabase.qhelp

Cleartext storage of sensitive information in a local database

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.

Recommendation

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.

Example

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.

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")

	// ...
}

References

@paldepind paldepind self-assigned this Dec 1, 2026
@geoffw0
geoffw0 marked this pull request as ready for review December 1, 2026 15:01
@geoffw0
geoffw0 requested a review from a team as a code owner December 1, 2026 15:01
Copilot AI adaptive review requested due to automatic review settings December 1, 2026 15:01
Copilot stopped reviewing on behalf of geoffw0 due to an error December 1, 2026 15:01
@geoffw0

geoffw0 commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

DCA LGTM. Results aren't perfect (as with cleartext logging), but OK for the initial version I think.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical sink-detection gaps leave Core Data and Realm writes unrecognized when framework declarations are absent, causing missed cleartext-storage alerts.

7 open issues
What changed in this PR

Ports Swift’s cleartext local-database storage query to Unified, using shared sensitive-data heuristics and data-flow models.

Changes:

  • Adds the query, help text, and encrypted-storage example.
  • Imports database and future transmission fixtures, with expectations documenting current detection gaps.
  • Disables three noisy SQLite.swift insert sink models.
File Description
unified/​ql/​test/​query-tests/​security/​CWE-311/​testURL.swift Adds URL transmission fixtures for follow-up work.
unified/​ql/​test/​query-tests/​security/​CWE-311/​testSwiftUI.swift Adds SwiftUI input transmission fixtures.
unified/​ql/​test/​query-tests/​security/​CWE-311/​testSend.swift Adds network-send transmission fixtures.
unified/​ql/​test/​query-tests/​security/​CWE-311/​testRealm2.swift Covers RealmSwift module inheritance cases.
unified/​ql/​test/​query-tests/​security/​CWE-311/​testRealm.swift Covers sensitive writes to Realm objects.
unified/​ql/​test/​query-tests/​security/​CWE-311/​testGRDB.swift Adds GRDB database-operation fixtures.
unified/​ql/​test/​query-tests/​security/​CWE-311/​testCoreData2.swift Covers managed properties and member-flow cases.
unified/​ql/​test/​query-tests/​security/​CWE-311/​testCoreData.swift Covers Core Data setters and sanitization.
unified/​ql/​test/​query-tests/​security/​CWE-311/​testAlamofire.swift Adds Alamofire transmission fixtures.
unified/​ql/​test/​query-tests/​security/​CWE-311/​sqlite3_c_api.swift Covers SQLite C statements and bindings.
unified/​ql/​test/​query-tests/​security/​CWE-311/​SQLite.swift Covers SQLite.swift statements, bindings, and writes.
unified/​ql/​test/​query-tests/​security/​CWE-311/​CONSISTENCY/​LocalSsaConsistency.expected Records SwiftUI consistency-check results.
unified/​ql/​test/​query-tests/​security/​CWE-311/​CleartextStorageDatabase.qlref Connects the query to inline-expectation checks.
unified/​ql/​test/​query-tests/​security/​CWE-311/​CleartextStorageDatabase.expected Records expected alerts and flow paths.
unified/​ql/​src/​queries/​security/​CWE-311/​CleartextStorageDatabase.swift Illustrates cleartext and encrypted storage.
unified/​ql/​src/​queries/​security/​CWE-311/​CleartextStorageDatabase.ql Implements sensitive-data flows to database sinks.
unified/​ql/​src/​queries/​security/​CWE-311/​CleartextStorageDatabase.qhelp Documents risks, recommendations, and the example.
unified/​ql/​lib/​ext/​database.model.json Disables three imprecise insert sink models.

Review effort: Max (adaptive)

bindingset[baseName]
private predicate isSubclassOf(ClassLikeDeclaration cls, string baseName) {
// TODO: if we want this predicate, it should probably be in a library?
cls.getABaseClass*().getName() = baseName
Comment on lines +33 to +35
target = TypeInference::resolveCallTarget(call) and
isSubclassOf(target.getEnclosingClass(), "NSManagedObject") and
target.getName() = ["setValue", "setPrimitiveValue"] and
* A taint-tracking configuration for cleartext database storage vulnerabilities.
*/
module CleartextStorageDatabaseConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node node) { node instanceof SensitiveData }
* A taint-tracking configuration for cleartext database storage vulnerabilities.
*/
module CleartextStorageDatabaseConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node node) { node instanceof SensitiveData }
// 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 on lines +87 to +92
exists(CallExpr call, FunctionDeclaration target, Expr argument |
target = TypeInference::resolveCallTarget(call) and
target.getName().regexpMatch("(?is).*(crypt|hash|encode|protect).*") and
argument = call.getAnArgument().getValue() and
node.asExpr() = argument
)

@paldepind paldepind left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A two minor comments, but overall looks good to me 👍

I didn't read all of the tests as they're just copied from the old Swift I assume they're fine :)

return sealedBox.combined!.base64EncodedString()
}

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes the formatting more consistent and idiomatic.

Suggested change
func storeMyData(databaseObject : NSManagedObject, faveSong : String, creditCardNo : String, encryptionKey: SymmetricKey) {
func storeMyData(databaseObject: NSManagedObject, faveSong: String, creditCardNo: String, encryptionKey: SymmetricKey) {


predicate isAdditionalFlowStep(DataFlow::Node nodeFrom, DataFlow::Node nodeTo) {
// propagate the taint from the base to the member access, e.g. from `sentitive` to `sensitive.field`
nodeTo.asExpr().(MemberAccessExpr).getBase() = nodeFrom.asExpr()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I might be wrong, but I think #23295 makes this not needed.

@geoffw0

geoffw0 commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I need to go through all the comments above, and also check whether #23296 has affected this PR before merging.

Update: Actually there are no new models here, so as long as there isn't a merge conflict we ought to be good.
Update 2: Merged main with no problems.

@@ -0,0 +1,37 @@
//codeql-extractor-options: -module-name RealmSwift

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@asgerf this line, which has been preserved from the original test, is supposed to make the stubs in this file appear to be in a module named RealmSwift so that class Object below can be identified as being the RealmSwift Object class in particular (not just any class called Object) - thus writes to class MyRealmSwiftObject3 are database writes.

I assume the line above doesn't even emulate this in the new extractor. How can we simulate this setup for the test?

Alternatively we might be able to get away with assuming Object is a typealias for RealmSwiftObject, if we can tell at the call site.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you mind leaving a TODO for the Realm sinks and let me address it in a follow up PR? We shouldn't work harder to recgonize the stubs, because it won't work in production.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation no-change-note-required This PR does not need a change note Unified

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants