Repository navigation
Unified: Port CleartextStorageDatabase query #23215
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
geoffw0
wants to merge
22
commits into
github:main
Choose a base branch
from
geoffw0:unifieddatabase
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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 80f7c5c
unified: Collect cleartext database models
geoffw0 3c5d758
unified: Port cleartext database query
geoffw0 c2339ec
unified: Detect direct database property writes
geoffw0 8364fb3
Unified: Pull the tests out of the CleartextStorageDatabase subdirect…
geoffw0 9a321e4
Unified: Add TODOs and comments, including some comments restored fro…
geoffw0 f07968f
Unified: Standardize on the alert message we use for rust.
geoffw0 ea4ef47
Unified: Simplify barrier implementation.
geoffw0 c138acc
Unified: Clean up test annotations.
geoffw0 9800cb4
Unified: Accept consistency test results.
geoffw0 c272ca1
Merge branch 'main' into unifieddatabase
geoffw0 44236a2
Unified: Disable a few models that are causing problems right now.
geoffw0 f582a61
Merge branch 'main' into unifieddatabase
geoffw0 a60e700
Unified: Accept .expected changes following merge.
geoffw0 5c26559
Unified: Fix a typo in the test, so that it tests the intended thing.
geoffw0 d25c964
Merge branch 'main' into unifieddatabase
geoffw0 f9b642f
Unified: Add stub-free test cases.
geoffw0 f91772e
Unified: Use Copilot recommended isSubclassOf implementation.
geoffw0 20a654c
Unified: Convert setValue models to MaD.
geoffw0 264f5b8
Update unified/ql/src/queries/security/CWE-311/CleartextStorageDataba…
geoffw0 62f2ce4
Unified: Remove the additional flow step (that is no longer needed).
geoffw0 85675f6
Unified: Autoformat.
geoffw0 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
32 changes: 32 additions & 0 deletions
32
unified/ql/src/queries/security/CWE-311/CleartextStorageDatabase.qhelp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
114
unified/ql/src/queries/security/CWE-311/CleartextStorageDatabase.ql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 } | ||
|
|
||
| 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 | ||
|
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() | ||
21 changes: 21 additions & 0 deletions
21
unified/ql/src/queries/security/CWE-311/CleartextStorageDatabase.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
|
|
||
| // ... | ||
| } |
6 changes: 6 additions & 0 deletions
6
unified/ql/test/query-tests/security/CWE-311/CONSISTENCY/LocalSsaConsistency.expected
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.