Skip to content
Draft
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>
120 changes: 120 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,120 @@
/**
* @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?
cls.getABaseClass*().getName() = baseName
}

/**
* Holds if `node` is a value stored through a Core Data API.
*/
private predicate coreDataSink(DataFlow::Node node) {
// values written into Core Data objects through `set*Value` methods are a sink.
exists(CallExpr call, FunctionDeclaration target |
target = TypeInference::resolveCallTarget(call) and
isSubclassOf(target.getEnclosingClass(), "NSManagedObject") and
target.getName() = ["setValue", "setPrimitiveValue"] and
node.asExpr() = call.getArgument(0).getValue()
)
or
// 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
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) }

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()
}

// 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