diff --git a/.github/workflows/codeql-qlt-unit-tests.yml b/.github/workflows/codeql-qlt-unit-tests.yml index 2a8b6ef7..e9a37422 100644 --- a/.github/workflows/codeql-qlt-unit-tests.yml +++ b/.github/workflows/codeql-qlt-unit-tests.yml @@ -54,7 +54,8 @@ 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 + # The `swift` extractor only runs on macOS, so `swift` tests cannot run on this ubuntu runner. + if [[ "$lang" == "ql" || "$lang" == "actions" || "$lang" == "swift" ]]; then echo "⚠️ qlt unit testing is not currently supported for language: $lang" continue fi diff --git a/languages/swift/custom/src/CredentialAndDataExposure/CredentialAndDataExposure.md b/languages/swift/custom/src/CredentialAndDataExposure/CredentialAndDataExposure.md new file mode 100644 index 00000000..86cab05c --- /dev/null +++ b/languages/swift/custom/src/CredentialAndDataExposure/CredentialAndDataExposure.md @@ -0,0 +1,60 @@ +# Credential and sensitive data exposure in an iOS application + +iOS applications often handle credentials, secrets and private information. Several common coding patterns expose that data to other applications, to the file system or to anyone with brief physical access to the device. This query (`swift/credential-and-data-exposure`) reports the following patterns: + +| Pattern | CWE | What is reported | +| -------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Sensitive data on the pasteboard | CWE-200 | A sensitive or decrypted value is written to `UIPasteboard` (`string`, `items`, `setValue(_:forPasteboardType:)`, `addItems(_:)`, `setItems(_:options:)`, ...) without the `.localOnly` or `.expirationDate` options. | +| Credential-derived session token | CWE-522 | A password flows into an `encrypt` function whose result is stored in a variable or property named like a token, session or cookie. | +| Missing background snapshot protection | CWE-200 | A `UIApplicationDelegate` does not implement `applicationDidEnterBackground(_:)` or `applicationWillResignActive(_:)` (and the app has no scene or notification based equivalent) although the app declares sensitive text inputs. | +| Weak keychain accessibility | CWE-922 | `SecItemAdd` is called in a file that never sets `kSecAttrAccessible`/`kSecAttrAccessControl`, or an item uses `kSecAttrAccessibleAlways`/`kSecAttrAccessibleAlwaysThisDeviceOnly`. | +| Sensitive response caching | CWE-922 | A request uses `.returnCacheDataElseLoad` or `.returnCacheDataDontLoad` in a function that handles sensitive data. | +| Sensitive data retained in memory | CWE-316 | A sensitive value is assigned to a `String`/`Data` property of a class, and that property is never cleared. | + +All patterns are heuristic, so the query has `low` precision and is intended for security audits and community packs. + +## Recommendation + +- Copy secrets to the pasteboard only with `setItems(_:options:)` and the `.localOnly` and `.expirationDate` options, or avoid copying them at all. +- Use random, server-issued session tokens. Never derive a token from the user's credentials, even with encryption. +- Obscure or clear sensitive views in `applicationDidEnterBackground(_:)`/`applicationWillResignActive(_:)` (or the scene delegate equivalents) so that the system snapshot does not capture them. +- Always set a restrictive `kSecAttrAccessible` value, such as `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`, when adding keychain items. +- Disable the session URL cache for requests that return sensitive data, for example by setting `urlCache` to `nil` on the `URLSessionConfiguration` or returning `nil` from `willCacheResponse`. `.reloadIgnoringLocalCacheData` only bypasses cache reads, and an ephemeral session avoids disk caching but can still cache in memory. +- Clear properties that hold sensitive values as soon as they are no longer needed. + +## Example + +The following code copies a decrypted secret to the general pasteboard, where any application can read it: + +```swift +@IBAction func copyValue(_ sender: AnyObject) { + UIPasteboard.general.string = self.decryptedValue // BAD +} +``` + +Instead, restrict the item to the local device and let it expire: + +```swift +@IBAction func copyValue(_ sender: AnyObject) { + UIPasteboard.general.setItems( + [[UIPasteboard.typeAutomatic: self.decryptedValue]], + options: [.localOnly: true, .expirationDate: Date(timeIntervalSinceNow: 60)]) // GOOD +} +``` + +The following code builds a session token by encrypting the user's email address and password: + +```swift +let userData = "\(info.email):\(info.password)" +let token = Crypto.encrypt(userData) // BAD +``` + +## References + +- OWASP MASVS: [MASVS-STORAGE](https://mas.owasp.org/MASVS/05-MASVS-STORAGE/). +- Apple: [Restricting keychain item accessibility](https://developer.apple.com/documentation/security/restricting-keychain-item-accessibility). +- Apple: [UIPasteboard.OptionsKey](https://developer.apple.com/documentation/uikit/uipasteboard/optionskey). +- Common Weakness Enumeration: [CWE-200](https://cwe.mitre.org/data/definitions/200.html). +- Common Weakness Enumeration: [CWE-316](https://cwe.mitre.org/data/definitions/316.html). +- Common Weakness Enumeration: [CWE-522](https://cwe.mitre.org/data/definitions/522.html). +- Common Weakness Enumeration: [CWE-922](https://cwe.mitre.org/data/definitions/922.html). diff --git a/languages/swift/custom/src/CredentialAndDataExposure/CredentialAndDataExposure.ql b/languages/swift/custom/src/CredentialAndDataExposure/CredentialAndDataExposure.ql new file mode 100644 index 00000000..916b0c5c --- /dev/null +++ b/languages/swift/custom/src/CredentialAndDataExposure/CredentialAndDataExposure.ql @@ -0,0 +1,420 @@ +/** + * @name Credential and sensitive data exposure in an iOS application + * @description Sensitive data copied to the shared pasteboard, session tokens derived from + * credentials, missing background snapshot protection, weak keychain + * accessibility, cached sensitive responses and sensitive values retained in + * long-lived properties can all expose credentials or private information. + * @kind problem + * @problem.severity warning + * @security-severity 5.5 + * @precision low + * @id swift/credential-and-data-exposure + * @tags security + * external/cwe/cwe-200 + * external/cwe/cwe-316 + * external/cwe/cwe-522 + * external/cwe/cwe-922 + */ + +import swift +import codeql.swift.dataflow.DataFlow +import codeql.swift.dataflow.TaintTracking +import codeql.swift.security.SensitiveExprs + +/** Holds if `name` looks like it holds plaintext that was decrypted from a protected store. */ +bindingset[name] +private predicate isDecryptedName(string name) { + name.regexpMatch("(?i).*(decrypt|plain.?text|clear.?text).*") +} + +/** Holds if `name` indicates sensitive data, according to the standard Swift heuristics. */ +bindingset[name] +private predicate isSensitiveName(string name) { + name.regexpMatch(any(SensitiveDataType t).getRegexp()) and + not name.regexpMatch(HeuristicNames::notSensitiveRegexp()) and + not name.regexpMatch("(?is).*(file|path|url|invalid).*") +} + +/** + * An expression that may contain sensitive data: either a standard `SensitiveExpr`, or a + * reference to a variable or function whose name indicates that it holds decrypted plaintext. + */ +private class SensitiveOrDecryptedExpr extends Expr { + string label; + + SensitiveOrDecryptedExpr() { + label = this.(SensitiveExpr).getLabel() + or + not this instanceof SensitiveExpr and + ( + label = this.(DeclRefExpr).getDecl().(VarDecl).getName() + or + label = this.(MemberRefExpr).getMember().(VarDecl).getName() + or + label = this.(ApplyExpr).getStaticTarget().(Function).getShortName() + ) and + isDecryptedName(label) + } + + string getLabel() { result = label } +} + +/* + * Pattern 1 (CWE-200): sensitive data copied to the shared pasteboard. + */ + +/** Holds if `e` is written to the system pasteboard. */ +private predicate isCallArgumentExpr(Expr e, CallExpr call) { + exists(Location exprLocation, Location argLocation, Argument arg | + arg = call.getAnArgument() and + exprLocation = e.getLocation() and + argLocation = arg.getExpr().getLocation() and + not exprLocation instanceof UnknownLocation and + exprLocation.getFile() = argLocation.getFile() and + exprLocation.getStartLine() >= argLocation.getStartLine() and + exprLocation.getEndLine() <= argLocation.getEndLine() and + ( + exprLocation.getStartLine() > argLocation.getStartLine() + or exprLocation.getStartColumn() >= argLocation.getStartColumn() + ) and + ( + exprLocation.getEndLine() < argLocation.getEndLine() + or exprLocation.getEndColumn() <= argLocation.getEndColumn() + ) + ) +} + +private predicate isPasteboardWrite(Expr e, Expr write) { + exists(AssignExpr assign, FieldDecl f | + assign.getDest().(MemberRefExpr).getMember() = f and + f.hasQualifiedName("UIPasteboard", + ["string", "strings", "url", "urls", "image", "images", "items", "color", "colors"]) and + e = assign.getSource() and + write = assign + ) + or + exists(CallExpr call | + call.getStaticTarget() + .(Method) + .hasQualifiedName("UIPasteboard", + [ + "setValue(_:forPasteboardType:)", "setData(_:forPasteboardType:)", "addItems(_:)", + "setItems(_:options:)", "setObjects(_:)", "setObjects(_:localOnly:expirationDate:)" + ]) and + e = call.getArgument(0).getExpr() and + write = call and + // Writes that restrict the item to the local device or set an expiration date are safe. + not exists(Expr opt | + isCallArgumentExpr(opt, call) and + ( + opt.(MemberRefExpr).getMember().(VarDecl).getName() = ["localOnly", "expirationDate"] or + opt.(DeclRefExpr).getDecl().(VarDecl).getName() = ["localOnly", "expirationDate"] + ) + ) and + not ( + call.getStaticTarget().(Method) + .hasQualifiedName("UIPasteboard", "setObjects(_:localOnly:expirationDate:)") and + ( + not exists(BooleanLiteralExpr localOnly | + localOnly = call.getArgumentWithLabel("localOnly").getExpr() and localOnly.getValue() = false + ) + or + not exists(NilLiteralExpr expirationDate | + expirationDate = call.getArgumentWithLabel("expirationDate").getExpr() + ) + ) + ) + ) +} + +private module PasteboardConfig implements DataFlow::ConfigSig { + predicate isSource(DataFlow::Node node) { node.asExpr() instanceof SensitiveOrDecryptedExpr } + + predicate isSink(DataFlow::Node node) { isPasteboardWrite(node.asExpr(), _) } + + predicate isBarrier(DataFlow::Node node) { + node.asExpr() instanceof EncryptedExpr or + node.asExpr().getType().getUnderlyingType() instanceof BoolType + } + + predicate isBarrierIn(DataFlow::Node node) { isSource(node) } + + predicate allowImplicitRead(DataFlow::Node node, DataFlow::ContentSet c) { + // sensitive data stored inside a collection (for example in `addItems`) is still copied. + isSink(node) and exists(c) + } + + predicate isAdditionalFlowStep(DataFlow::Node nodeFrom, DataFlow::Node nodeTo) { + // if an object is sensitive, its fields are always sensitive. + nodeTo.asExpr().(MemberRefExpr).getBase() = nodeFrom.asExpr() + } +} + +private module PasteboardFlow = TaintTracking::Global; + +/* + * Pattern 2 (CWE-522): a session token derived by reversibly encrypting user credentials. + */ + +/** A call to a function that encrypts data (but not one that decrypts it). */ +private class EncryptCall extends CallExpr { + EncryptCall() { + exists(string name | name = this.getStaticTarget().(Function).getShortName() | + name.regexpMatch("(?i).*encrypt.*") and + not name.regexpMatch("(?i).*decrypt.*") + ) + } +} + +/** Holds if `name` looks like the name of a session/authentication token. */ +bindingset[name] +private predicate isTokenName(string name) { name.regexpMatch("(?i).*(token|session|cookie).*") } + +/** Holds if the result of `call` is stored in a variable or property named like a session token. */ +private predicate isTokenProducingCall(EncryptCall call) { + exists(Expr ref | + DataFlow::localExprFlow(call, ref) and + ( + isTokenName(ref.(DeclRefExpr).getDecl().(VarDecl).getName()) or + isTokenName(ref.(MemberRefExpr).getMember().(VarDecl).getName()) + ) + ) + or + exists(AssignExpr assign | + assign.getSource() = call and + isTokenName(assign.getDest().(MemberRefExpr).getMember().(VarDecl).getName()) + ) + or + exists(VarDecl v | v.getParentInitializer() = call and isTokenName(v.getName())) +} + +private module CredentialTokenConfig implements DataFlow::ConfigSig { + predicate isSource(DataFlow::Node node) { + node.asExpr().(SensitiveExpr).getSensitiveType() instanceof SensitivePassword + } + + predicate isSink(DataFlow::Node node) { + exists(EncryptCall call | + isTokenProducingCall(call) and + node.asExpr() = call.getAnArgument().getExpr() + ) + } + + predicate isBarrierIn(DataFlow::Node node) { isSource(node) } + + predicate isAdditionalFlowStep(DataFlow::Node nodeFrom, DataFlow::Node nodeTo) { + nodeTo.asExpr().(MemberRefExpr).getBase() = nodeFrom.asExpr() + } +} + +private module CredentialTokenFlow = TaintTracking::Global; + +/* + * Pattern 3 (CWE-200): application delegate that does not obscure the window when backgrounded. + */ + +/** A class that conforms to `UIApplicationDelegate`. */ +private class AppDelegateClass extends ClassDecl { + AppDelegateClass() { this.getABaseTypeDecl*().getName() = "UIApplicationDelegate" } + + /** Gets a member of this class or of one of its extensions. */ + Decl getAnyMember() { + result = this.getAMember() + or + exists(ExtensionDecl ext | ext.getExtendedTypeDecl() = this and result = ext.getAMember()) + } +} + +/** Holds if the application obscures or clears its UI when it moves to the background. */ +private predicate obscuresOnBackground(AppDelegateClass delegate) { + delegate.getAnyMember().(Method).getName() = + ["applicationDidEnterBackground(_:)", "applicationWillResignActive(_:)"] +} + +/** Holds if the program protects its UI on backgrounding outside of the application delegate. */ +private predicate obscuresOnBackgroundElsewhere() { + exists(Method m | + m.getName() = ["sceneDidEnterBackground(_:)", "sceneWillResignActive(_:)"] and + exists(m.getBody()) + ) + or + exists(MemberRefExpr ref | + not ref.getLocation() instanceof UnknownLocation and + ref.getMember().(VarDecl).getName() = + [ + "didEnterBackgroundNotification", "willResignActiveNotification", + "UIApplicationDidEnterBackground", "UIApplicationWillResignActive" + ] + ) +} + +/** A text input property whose name indicates that the user enters sensitive data into it. */ +private class SensitiveInputField extends VarDecl { + SensitiveInputField() { + this.getType().getName().regexpMatch(".*\\bUIText(Field|View)\\b.*") and + exists(string name | name = this.getName() | + isSensitiveName(name) or + name.regexpMatch("(?i).*(security|secret).?answer.*") + ) + } +} + +/* + * Pattern 4 (CWE-922): keychain items without a restrictive accessibility attribute. + */ + +/** Holds if `file` references a keychain accessibility attribute. */ +private predicate fileSetsKeychainAccessibility(File file) { + exists(DeclRefExpr ref | + ref.getDecl().(VarDecl).getName() = ["kSecAttrAccessible", "kSecAttrAccessControl"] and + ref.getFile() = file + ) +} + +/* + * Pattern 5 (CWE-922): sensitive responses stored in the shared URL cache. + */ + +/** Holds if `f` handles sensitive data, so that responses it requests may be sensitive. */ +private predicate handlesSensitiveData(Function f) { + exists(SensitiveExpr e | e.getEnclosingFunction() = f) + or + exists(StringLiteralExpr s | + s.getEnclosingFunction() = f and + s.getValue() + .regexpMatch("(?i).*\\b(token|key|password|passwd|secret|session|credentials?|auth)\\b.*") + ) +} + +/* + * Pattern 6 (CWE-316): sensitive data retained in a long-lived class property. + */ + +/** A stored property of a class whose name indicates that it holds sensitive data. */ +private class SensitiveClassProperty extends VarDecl { + SensitiveClassProperty() { + this.getDeclaringDecl() instanceof ClassDecl and + isSensitiveName(this.getName()) and + this.getType() + .getUnderlyingType() + .getName() + .regexpMatch("(String|NSString|NSMutableString|Data|NSData|NSMutableData|\\[UInt8\\]|\\[Character\\])[?!]?") + } +} + +/** Holds if `e` clears the value of a property when assigned to it. */ +private predicate isClearingValue(Expr e) { + e instanceof NilLiteralExpr or + e.(StringLiteralExpr).getValue() = "" or + e.(ArrayExpr).getNumberOfElements() = 0 or + ( + e.(CallExpr).getStaticTarget() instanceof Initializer and + e.(CallExpr).getNumberOfArguments() = 0 + ) +} + +/** Holds if `v` is cleared somewhere in the program. */ +private predicate isCleared(SensitiveClassProperty v) { + exists(AssignExpr assign | + assign.getDest().(MemberRefExpr).getMember() = v and + isClearingValue(assign.getSource().getFullyUnresolved()) + ) + or + exists(MethodCallExpr call | + call.getQualifier().(MemberRefExpr).getMember() = v and + call.getStaticTarget().getShortName() = ["removeAll", "resetBytes"] + ) +} + +from AstNode alert, string message, AstNode related, string relatedLabel +where + ( + // Pattern 1: pasteboard. + exists(DataFlow::Node source, DataFlow::Node sink | + PasteboardFlow::flow(source, sink) and + isPasteboardWrite(sink.asExpr(), alert) and + message = + "Sensitive data from $@ is copied to the shared pasteboard without an expiration date or local-only restriction." and + related = source.asExpr() and + relatedLabel = source.asExpr().(SensitiveOrDecryptedExpr).getLabel() + ) + or + // Pattern 2: credential-derived session token. + exists(DataFlow::Node source, DataFlow::Node sink, EncryptCall call | + CredentialTokenFlow::flow(source, sink) and + sink.asExpr() = call.getAnArgument().getExpr() and + alert = call and + message = + "This session token is derived by reversibly encrypting $@; use a random, server-issued token instead." and + related = source.asExpr() and + relatedLabel = source.asExpr().(SensitiveExpr).getLabel() + ) + or + // Pattern 3: no background snapshot protection. + exists(AppDelegateClass delegate, SensitiveInputField field | + not obscuresOnBackground(delegate) and + not obscuresOnBackgroundElsewhere() and + field = + min(SensitiveInputField f | + | + f + order by + f.getLocation().getFile().getAbsolutePath(), f.getLocation().getStartLine(), + f.getLocation().getStartColumn() + ) and + alert = delegate and + message = + "This application delegate does not obscure the window when the app enters the background, so the system snapshot may capture sensitive input such as $@." and + related = field and + relatedLabel = field.getName() + ) + or + // Pattern 4a: keychain item added without an explicit accessibility attribute. + exists(CallExpr call | + call.getStaticTarget().(Function).getName() = "SecItemAdd(_:_:)" and + not fileSetsKeychainAccessibility(call.getFile()) and + alert = call and + message = + "This keychain item is added using $@ without a restrictive kSecAttrAccessible value, so the default accessibility applies." and + related = call.getArgument(0).getExpr() and + relatedLabel = "this attribute dictionary" + ) + or + // Pattern 4b: keychain item that is always accessible. + exists(DeclRefExpr ref, string name | + name = ref.getDecl().(VarDecl).getName() and + name = ["kSecAttrAccessibleAlways", "kSecAttrAccessibleAlwaysThisDeviceOnly"] and + alert = ref and + message = + "This keychain item uses the accessibility class $@, which leaves it readable while the device is locked." and + related = ref and + relatedLabel = name + ) + or + // Pattern 5: sensitive response cached. + exists(EnumElementExpr e, Function f | + e.getElement().getName() = ["returnCacheDataElseLoad", "returnCacheDataDontLoad"] and + f = e.getEnclosingFunction() and + handlesSensitiveData(f) and + alert = e and + message = + "This request uses a cache policy that serves stored responses, so sensitive data handled in $@ may be persisted in the shared URL cache." and + related = f and + relatedLabel = f.getName() + ) + or + // Pattern 6: sensitive value retained in memory. + exists(AssignExpr assign, SensitiveClassProperty v | + assign.getDest().(MemberRefExpr).getMember() = v and + not isClearingValue(assign.getSource().getFullyUnresolved()) and + not isCleared(v) and + alert = assign and + message = + "Sensitive data is stored in the long-lived property $@, which is never cleared after use." and + related = v and + relatedLabel = v.getName() + ) + ) and + // ignore compiler-synthesized code, such as implicit property accessors. + not alert.getLocation() instanceof UnknownLocation +select alert, message, related, relatedLabel diff --git a/languages/swift/custom/src/qlpack.yml b/languages/swift/custom/src/qlpack.yml new file mode 100644 index 00000000..397f59b7 --- /dev/null +++ b/languages/swift/custom/src/qlpack.yml @@ -0,0 +1,5 @@ +name: languages-swift-custom-src +version: 0.0.2 +library: false +dependencies: + codeql/swift-all: "*" diff --git a/languages/swift/custom/test/CredentialAndDataExposure/CredentialAndDataExposure.expected b/languages/swift/custom/test/CredentialAndDataExposure/CredentialAndDataExposure.expected new file mode 100644 index 00000000..26dd798b --- /dev/null +++ b/languages/swift/custom/test/CredentialAndDataExposure/CredentialAndDataExposure.expected @@ -0,0 +1,14 @@ +| CredentialAndDataExposure/keychain_accessible.swift:30:25:30:25 | kSecAttrAccessibleAlways | This keychain item uses the accessibility class $@, which leaves it readable while the device is locked. | CredentialAndDataExposure/keychain_accessible.swift:30:25:30:25 | kSecAttrAccessibleAlways | kSecAttrAccessibleAlways | +| CredentialAndDataExposure/test.swift:93:5:93:22 | ... = ... | Sensitive data from $@ is copied to the shared pasteboard without an expiration date or local-only restriction. | CredentialAndDataExposure/test.swift:93:17:93:22 | .decryptedValue | decryptedValue | +| CredentialAndDataExposure/test.swift:101:5:101:77 | call to setValue(_:forPasteboardType:) | Sensitive data from $@ is copied to the shared pasteboard without an expiration date or local-only restriction. | CredentialAndDataExposure/test.swift:101:35:101:35 | password | password | +| CredentialAndDataExposure/test.swift:102:5:102:62 | call to addItems(_:) | Sensitive data from $@ is copied to the shared pasteboard without an expiration date or local-only restriction. | CredentialAndDataExposure/test.swift:102:52:102:52 | password | password | +| CredentialAndDataExposure/test.swift:111:5:111:35 | ... = ... | Sensitive data from $@ is copied to the shared pasteboard without an expiration date or local-only restriction. | CredentialAndDataExposure/test.swift:110:17:110:35 | call to decryptString(_:) | decryptString | +| CredentialAndDataExposure/test.swift:127:17:127:40 | call to encrypt(_:) | This session token is derived by reversibly encrypting $@; use a random, server-issued token instead. | CredentialAndDataExposure/test.swift:126:37:126:42 | .password | password | +| CredentialAndDataExposure/test.swift:132:25:132:53 | call to encrypt(_:) | This session token is derived by reversibly encrypting $@; use a random, server-issued token instead. | CredentialAndDataExposure/test.swift:132:40:132:45 | .password | password | +| CredentialAndDataExposure/test.swift:148:1:154:1 | AppDelegate | This application delegate does not obscure the window when the app enters the background, so the system snapshot may capture sensitive input such as $@. | CredentialAndDataExposure/test.swift:182:12:182:12 | securityAnswerField | securityAnswerField | +| CredentialAndDataExposure/test.swift:194:16:194:39 | call to SecItemAdd(_:_:) | This keychain item is added using $@ without a restrictive kSecAttrAccessible value, so the default accessibility applies. | CredentialAndDataExposure/test.swift:194:27:194:27 | newItem | this attribute dictionary | +| CredentialAndDataExposure/test.swift:205:30:205:31 | .returnCacheDataElseLoad | This request uses a cache policy that serves stored responses, so sensitive data handled in $@ may be persisted in the shared URL cache. | CredentialAndDataExposure/test.swift:202:3:207:3 | fetchKey() | fetchKey() | +| CredentialAndDataExposure/test.swift:217:56:217:57 | .returnCacheDataDontLoad | This request uses a cache policy that serves stored responses, so sensitive data handled in $@ may be persisted in the shared URL cache. | CredentialAndDataExposure/test.swift:215:3:219:3 | fetchCredentials(password:) | fetchCredentials(password:) | +| CredentialAndDataExposure/test.swift:236:5:236:58 | ... = ... | Sensitive data is stored in the long-lived property $@, which is never cleared after use. | CredentialAndDataExposure/test.swift:231:7:231:7 | cardNumberString | cardNumberString | +| CredentialAndDataExposure/test.swift:256:5:256:86 | call to setObjects(_:localOnly:expirationDate:) | Sensitive data from $@ is copied to the shared pasteboard without an expiration date or local-only restriction. | CredentialAndDataExposure/test.swift:256:38:256:38 | password | password | +| CredentialAndDataExposure/test.swift:271:5:271:40 | ... = ... | Sensitive data is stored in the long-lived property $@, which is never cleared after use. | CredentialAndDataExposure/test.swift:263:7:263:7 | passwordString | passwordString | diff --git a/languages/swift/custom/test/CredentialAndDataExposure/CredentialAndDataExposure.qlref b/languages/swift/custom/test/CredentialAndDataExposure/CredentialAndDataExposure.qlref new file mode 100644 index 00000000..469bbb80 --- /dev/null +++ b/languages/swift/custom/test/CredentialAndDataExposure/CredentialAndDataExposure.qlref @@ -0,0 +1,2 @@ +query: CredentialAndDataExposure/CredentialAndDataExposure.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/swift/custom/test/CredentialAndDataExposure/keychain_accessible.swift b/languages/swift/custom/test/CredentialAndDataExposure/keychain_accessible.swift new file mode 100644 index 00000000..faa762a9 --- /dev/null +++ b/languages/swift/custom/test/CredentialAndDataExposure/keychain_accessible.swift @@ -0,0 +1,33 @@ +// --- stubs --- + +typealias OSStatus = Int32 +typealias CFDictionary = [String : Any] + +let kSecClass: String = "class" +let kSecClassGenericPassword: String = "genp" +let kSecValueData: String = "v_Data" +let kSecAttrAccessible: String = "pdmn" +let kSecAttrAccessibleWhenUnlockedThisDeviceOnly: String = "aku" +let kSecAttrAccessibleAlways: String = "dk" + +func SecItemAdd(_ attributes: CFDictionary, _ result: UnsafeMutablePointer?) -> OSStatus { return 0 } + +// --- tests --- + +func savePasswordSafely(_ encodedPassword: String) { + let item: [String : Any] = [ + kSecClass: kSecClassGenericPassword, + kSecValueData: encodedPassword, + kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly + ] + let status = SecItemAdd(item, nil) // GOOD (restrictive accessibility set) +} + +func savePasswordAlways(_ encodedPassword: String) { + let item: [String : Any] = [ + kSecClass: kSecClassGenericPassword, + kSecValueData: encodedPassword, + kSecAttrAccessible: kSecAttrAccessibleAlways // $ Alert[swift/credential-and-data-exposure] + ] + let status = SecItemAdd(item, nil) +} diff --git a/languages/swift/custom/test/CredentialAndDataExposure/test.swift b/languages/swift/custom/test/CredentialAndDataExposure/test.swift new file mode 100644 index 00000000..b581770a --- /dev/null +++ b/languages/swift/custom/test/CredentialAndDataExposure/test.swift @@ -0,0 +1,288 @@ +// --- stubs --- + +class NSObject {} + +class UIResponder : NSObject {} + +class UIView : UIResponder {} + +class UIWindow : UIView {} + +class UIViewController : UIResponder {} + +class UITextField : UIView { + var text: String? + var isSecureTextEntry: Bool = false +} + +class UIApplication : NSObject { +} + +protocol UIApplicationDelegate {} + +class UIPasteboard : NSObject { + struct OptionsKey : Hashable { + let rawValue: String + static let expirationDate = OptionsKey(rawValue: "expirationDate") + static let localOnly = OptionsKey(rawValue: "localOnly") + } + + class var general: UIPasteboard { return UIPasteboard() } + + var string: String? + var strings: [String]? + var items: [[String : Any]] = [] + + func setValue(_ value: Any, forPasteboardType pasteboardType: String) {} + func setItems(_ items: [[String : Any]], options: [UIPasteboard.OptionsKey : Any] = [:]) {} + func addItems(_ items: [[String : Any]]) {} +} + +struct Date { + init(timeIntervalSinceNow: Double) {} +} + +struct URL { + init?(string: String) {} +} + +struct Data {} + +extension String { + func data(using encoding: Int) -> Data? { return Data() } +} + +struct URLRequest { + enum CachePolicy { + case useProtocolCachePolicy + case reloadIgnoringLocalCacheData + case returnCacheDataElseLoad + case returnCacheDataDontLoad + } + + init(url: URL, cachePolicy: CachePolicy = .useProtocolCachePolicy, timeoutInterval: Double = 60.0) {} + + var cachePolicy: CachePolicy = .useProtocolCachePolicy + var httpBody: Data? +} + +typealias OSStatus = Int32 +typealias CFDictionary = [String : Any] + +let kSecClass: String = "class" +let kSecClassGenericPassword: String = "genp" +let kSecAttrAccount: String = "acct" +let kSecValueData: String = "v_Data" + +func SecItemAdd(_ attributes: CFDictionary, _ result: UnsafeMutablePointer?) -> OSStatus { return 0 } + +class Crypto { + static func encrypt(_ data: String) -> String { return data } +} + +func decryptString(_ value: String) -> String { return value } + +// --- pasteboard --- + +class SecretItemViewController : UIViewController { + var decryptedValue: String = "" + var itemName: String = "" + + func copyValue() { + let pb: UIPasteboard = UIPasteboard.general + pb.string = self.decryptedValue // $ Alert[swift/credential-and-data-exposure] + } + + func copyName() { + UIPasteboard.general.string = itemName // GOOD (not sensitive) + } + + func copyPassword(password: String) { + UIPasteboard.general.setValue(password, forPasteboardType: "public.text") // $ Alert[swift/credential-and-data-exposure] + UIPasteboard.general.addItems([["public.text": password]]) // $ Alert[swift/credential-and-data-exposure] + } + + func copyPasswordWithExpiry(password: String) { + UIPasteboard.general.setItems([["public.text": password]], options: [.localOnly: true, .expirationDate: Date(timeIntervalSinceNow: 60)]) // GOOD (local-only and expiring) + } + + func copyDecrypted(item: String) { + let plain = decryptString(item) + UIPasteboard.general.string = plain // $ Alert[swift/credential-and-data-exposure] + } +} + +// --- session token --- + +struct SignInModel { + var email: String + var password: String +} + +class NetworkCalls { + var sessionToken: String = "" + + func auth(_ info: SignInModel, handler: (String) -> Void) { + let userData = "\(info.email):\(info.password)" + let token = Crypto.encrypt(userData) // $ Alert[swift/credential-and-data-exposure] + handler(token) + } + + func auth2(_ info: SignInModel) { + self.sessionToken = Crypto.encrypt(info.password) // $ Alert[swift/credential-and-data-exposure] + } + + func storeBlob(_ info: SignInModel) -> String { + let encryptedBlob = Crypto.encrypt(info.password) // GOOD (not used as a session token) + return encryptedBlob + } + + func authWithServerToken(_ info: SignInModel, serverResponse: String) { + let token = Crypto.encrypt(serverResponse) // GOOD (not derived from credentials) + self.sessionToken = token + } +} + +// --- app delegate --- + +class AppDelegate : UIResponder, UIApplicationDelegate { // BAD (alert spans the class declaration and is matched on its last line) + var window: UIWindow? + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [String : Any]?) -> Bool { + return true + } +} // $ Alert[swift/credential-and-data-exposure] + +extension AppDelegate { + func configureRootController() { + self.window = UIWindow() + } +} + +class SafeAppDelegate : UIResponder, UIApplicationDelegate { // GOOD (obscures the window on backgrounding) + var window: UIWindow? + var privacyView: UIView? + + func applicationDidEnterBackground(_ application: UIApplication) { + privacyView = UIView() + } +} + +class SafeAppDelegate2 : UIResponder, UIApplicationDelegate { + var window: UIWindow? +} + +extension SafeAppDelegate2 { // GOOD (obscures the window from an extension) + func applicationWillResignActive(_ application: UIApplication) { + window = nil + } +} + +class ResetPasswordViewController : UIViewController { + weak var securityAnswerField: UITextField! + weak var passwordField: UITextField! + weak var nameField: UITextField! +} + +// --- keychain missing --- + +func savePassword(_ encodedPassword: Data) { + var newItem = [String : Any]() + newItem[kSecClass] = kSecClassGenericPassword + newItem[kSecAttrAccount] = "user" + newItem[kSecValueData] = encodedPassword + let status = SecItemAdd(newItem, nil) // $ Alert[swift/credential-and-data-exposure] +} + +// --- caching --- + +class KeyFetcher { + let demoEndpoint = "http://localhost:8081/webkit.php" + + func fetchKey() { + guard let url = URL(string: demoEndpoint) else { return } + var urlRequest = URLRequest(url: url) + urlRequest.cachePolicy = .returnCacheDataElseLoad // $ Alert[swift/credential-and-data-exposure] + urlRequest.httpBody = "token=key".data(using: 4) + } + + func fetchKeyNoCache() { + guard let url = URL(string: demoEndpoint) else { return } + var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData) // GOOD (bypasses cache reads) + urlRequest.httpBody = "token=key".data(using: 4) + } + + func fetchCredentials(password: String) { + guard let url = URL(string: demoEndpoint) else { return } + let urlRequest = URLRequest(url: url, cachePolicy: .returnCacheDataDontLoad) // $ Alert[swift/credential-and-data-exposure] + let body = password.data(using: 4) + } + + func fetchImages() { + guard let url = URL(string: "http://localhost:8081/logo.png") else { return } + let urlRequest = URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad) // GOOD (not sensitive) + } +} + +// --- memory --- + +class MemoryManagementVC : UIViewController { + weak var cardNoTextField: UITextField! + var cardNumberString: String = "" + var clearedCardNumber: String = "" + var itemName: String = "" + + func payItemPressed() { + self.cardNumberString = self.cardNoTextField.text ?? "" // $ Alert[swift/credential-and-data-exposure] + self.itemName = self.cardNoTextField.text ?? "" // GOOD (not sensitive) + } + + func payAndClear() { + clearedCardNumber = cardNoTextField.text ?? "" // GOOD (cleared below) + } + + func viewWillDisappear() { + clearedCardNumber = "" + } +} + +extension UIPasteboard { + func setObjects(_ objects: [Any], localOnly: Bool, expirationDate: Date?) {} +} + +extension SecretItemViewController { + func copyWithCallSpecificOptions(password: String) { + UIPasteboard.general.setItems([["public.text": password]], options: [.localOnly: true]) // GOOD (protected write) + UIPasteboard.general.setObjects([password], localOnly: false, expirationDate: nil) // $ Alert[swift/credential-and-data-exposure] + UIPasteboard.general.setObjects([password], localOnly: true, expirationDate: nil) // GOOD (local-only) + UIPasteboard.general.setObjects([password], localOnly: false, expirationDate: Date(timeIntervalSinceNow: 60)) // GOOD (expiring) + } +} + +class MemoryManagementRegressionVC : UIViewController { + var passwordString: String = "" + var clearedPassword: String = "" + var passwordData: Data = Data() + var passwordBytes: [UInt8] = [] + + func loadPassword() -> String { return "" } + + func assignLoadedPassword() { + self.passwordString = loadPassword() // $ Alert[swift/credential-and-data-exposure] + } + + func clearPassword(_ secret: String) { + self.clearedPassword = secret + self.clearedPassword = String() + } + + func clearData(_ secret: Data) { + self.passwordData = secret + self.passwordData = Data() + } + + func clearBytes(_ secret: [UInt8]) { + self.passwordBytes = secret + self.passwordBytes = [UInt8]() + } +} diff --git a/languages/swift/custom/test/qlpack.yml b/languages/swift/custom/test/qlpack.yml new file mode 100644 index 00000000..8f8e1af6 --- /dev/null +++ b/languages/swift/custom/test/qlpack.yml @@ -0,0 +1,5 @@ +name: languages-swift-custom-test +version: 0.0.2 +dependencies: + languages-swift-custom-src: ${workspace} +extractor: swift