Swift Weak Keychain Accessibility

Weak Keychain accessibility settings in Swift

Description

The kSecAttrAccessibleAlways family allows the app to read Keychain items while the device is locked. This increases exposure on a lost or jailbroken device. Items that can migrate in a backup may also be exposed on another device.

Potential impact

  • Access to Keychain items while the device is locked
  • Sensitive data exposure following device loss or backup restoration
  • Reuse of stolen tokens or passwords

Remediation

  • For a sensitive item needed only while the device is unlocked, prefer kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly. It requires a device passcode.
  • If a background task must read the item while locked, consider kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly. On a device with a passcode, it becomes available after the first unlock following a restart. Both device-only settings prevent migration to another device through a backup.

Examples

Before

swift
query[kSecAttrAccessible as String] = kSecAttrAccessibleAlways

After

swift
import Foundation
import Security

enum KeychainStorageError: Error {
    case unexpectedStatus(OSStatus)
}

func saveToken(_ token: Data) throws {
    let item: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: "com.example.app.auth",
        kSecAttrAccount as String: "access_token",
        kSecAttrAccessible as String:
            kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
        kSecValueData as String: token
    ]

    let addStatus = SecItemAdd(item as CFDictionary, nil)
    if addStatus == errSecSuccess { return }
    guard addStatus == errSecDuplicateItem else {
        throw KeychainStorageError.unexpectedStatus(addStatus)
    }

    let match: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: "com.example.app.auth",
        kSecAttrAccount as String: "access_token"
    ]
    let updates: [String: Any] = [
        kSecAttrAccessible as String:
            kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
        kSecValueData as String: token
    ]
    let updateStatus = SecItemUpdate(
        match as CFDictionary, updates as CFDictionary)
    guard updateStatus == errSecSuccess else {
        throw KeychainStorageError.unexpectedStatus(updateStatus)
    }
}

saveToken applies the same accessibility setting when adding a token and when updating an existing one. If an operation fails, including when no passcode is set, the function throws.

References