SPB Git

Repository Public

Vault.swift 44.5 KB 929 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraVault/Vault.swift8// Module           : Qyvora Vault9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMath43import QyvoraStorage4445/// Conversion of a date to the whole seconds stored in the vault and backup formats (unsigned 64-bit).46public enum VaultTime {47    /// Seconds since 1970, saturating: a date before 1970 (or not a number) gives 0 and a date beyond the 64-bit range48    /// gives `UInt64.max`. The conversion never traps, whatever date a restored record carries: a stored value close49    /// to 2^64 reads back as a `Date` whose interval rounds up to 2^64, which `UInt64(_:)` refuses.50    public static func seconds(_ date: Date) -> UInt64 {51        let t = date.timeIntervalSince197052        guard t > 0 else { return 0 }53        return t < 18_446_744_073_709_551_616.0 ? UInt64(t) : UInt64.max54    }55}5657/// A reading of a clock the holder of the device cannot set (QYV-SVC-010): continuous time since boot, sleep included,58/// with the identifier of the boot session it belongs to. Two readings are comparable only within one boot session.59public struct MonotonicInstant: Sendable, Equatable {60    /// Identifier of the boot session (16 bytes), empty when the system does not give one.61    public var bootSession: Bytes62    /// Whole seconds since boot, counted while the device sleeps too.63    public var seconds: UInt646465    public init(bootSession: Bytes, seconds: UInt64) {66        self.bootSession = bootSession67        self.seconds = seconds68    }6970    /// `clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW)` (mach continuous time: not settable, runs during sleep, restarts71    /// at boot) and `kern.bootsessionuuid`.72    public static func system() -> MonotonicInstant {73        let seconds = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) / 1_000_000_00074        var size = 075        guard sysctlbyname("kern.bootsessionuuid", nil, &size, nil, 0) == 0, size > 0, size <= 64 else {76            return MonotonicInstant(bootSession: [], seconds: seconds)77        }78        var buffer = [CChar](repeating: 0, count: size)79        guard sysctlbyname("kern.bootsessionuuid", &buffer, &size, nil, 0) == 0 else { return MonotonicInstant(bootSession: [], seconds: seconds) }80        let text = String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)81        return MonotonicInstant(bootSession: UUID(uuidString: text).map(\.bytes16) ?? [], seconds: seconds)82    }83}8485/// When the application should lock the vault by itself.86public enum AutoLockPolicy: Sendable, Equatable, Codable {87    /// Lock as soon as the application leaves the foreground or the check runs.88    case immediately89    /// Lock after this many seconds without activity.90    case after(seconds: TimeInterval)91    case never92}9394/// PIN policy. The escalating delays are fixed; erasing the vault after N wrong PINs is optional and off by default.95public struct PINPolicy: Sendable, Equatable {96    /// Erase the vault from this device after this many consecutive wrong PINs. Nil (default) never erases.97    public var wipeAfterFailedAttempts: Int?9899    public init(wipeAfterFailedAttempts: Int? = nil) {100        self.wipeAfterFailedAttempts = wipeAfterFailedAttempts101    }102103    public static let minimumPINLength = 6104105    /// How far the wall clock may run ahead of (or behind) the monotonic clock over a waiting period before the two are106    /// held to disagree (seconds). The decision to let an attempt through never depends on it: it only decides107    /// whether a pending delay is restarted in full.108    public static let clockDisagreementTolerance: TimeInterval = 30109110    /// Waiting time imposed after `n` consecutive failures: none for the first two, then111    /// 1 min (3), 5 min (4), 15 min (5), 1 h (6), 3 h (7), 24 h (8 and more).112    /// Three attempts are therefore free; the fourth must wait one minute after the third failure.113    public static func delay(afterFailedAttempts n: Int) -> TimeInterval {114        switch n {115        case ..<3: return 0116        case 3: return 60117        case 4: return 300118        case 5: return 900119        case 6: return 3600120        case 7: return 3 * 3600121        default: return 24 * 3600122        }123    }124}125126/// Public, secret-free description of a vault for the Quantum Shield.127public struct VaultReport: Sendable, Equatable, Codable {128    public struct KDF: Sendable, Equatable, Codable {129        public let construction: String130        public let parameters: KDFParameters131    }132133    public let formatVersion: Int134    public let vaultID: String135    public let createdAt: Date136    public let keyEpoch: UInt32137    public let generation: UInt64138    public let isUnlocked: Bool139    public let recordEncryption: String140    public let sealingBackend: String141    public let nonceBits: Int142    public let masterKeyBits: Int143    public let subkeyDerivation: String144    public let fileAuthentication: String145    public let passwordSlot: KDF?146    public let pinSlot: KDF?147    public let deviceSlotEnabled: Bool148    public let deviceSlotUsesSecureEnclave: Bool149    public let pinFailedAttempts: Int?150    public let pinWipeAfterFailedAttempts: Int?151    public let recordCounts: [String: Int]152    public let totalRecords: Int153    /// True when the current file was damaged and this session runs on the `.previous` copy.154    public let recoveredFromPreviousCopy: Bool155    public let selfTestPassed: Bool156}157158/// Result of `Vault.rotateMasterKey`.159public struct KeyRotationResult: Sendable, Equatable {160    public let newKeyEpoch: UInt32161    public let recordsReencrypted: Int162    /// False when a PIN slot existed and was removed because the PIN was not supplied for re-wrapping.163    public let pinSlotKept: Bool164}165166/// Result of `Vault.verifyIntegrity`.167public struct IntegrityReport: Sendable, Equatable {168    public let recordsVerified: Int169    public let generation: UInt64170}171172/// The Quantum Vault: one encrypted file holding every secret of the wallet, with independent unlock slots.173///174/// An actor: all operations are serialized. Every method throws `VaultError` only.175/// Password and PIN derivations are deliberately slow (hundreds of milliseconds to seconds); call them off the main actor.176public actor Vault {177    public struct Configuration: Sendable {178        public var fileName: String179        /// Cost of new password and PIN slots (existing slots keep the parameters stored in their header).180        public var kdf: KDFParameters181        /// Implementation that seals. `.system` (CryptoKit) by default.182        public var aead: AEADKind183        /// Wall clock, injectable for tests.184        public var now: @Sendable () -> Date185        /// Clock the user cannot set, used for the PIN delays; injectable for tests.186        public var monotonic: @Sendable () -> MonotonicInstant187        /// Highest key-derivation cost accepted from the header of a vault file, and for new slots (QYV-SVC-012).188        public var kdfCeiling: KDFParameters = .deviceCeiling189190        public init(191            fileName: String = "vault.qyv", kdf: KDFParameters = .standard, aead: AEADKind = .system,192            now: @escaping @Sendable () -> Date = { Date() },193            monotonic: @escaping @Sendable () -> MonotonicInstant = { MonotonicInstant.system() }194        ) {195            self.fileName = fileName196            self.kdf = kdf197            self.aead = aead198            self.now = now199            self.monotonic = monotonic200        }201    }202203    private let fileStore: FileStore204    private let keychain: any KeychainStore205    private let secureEnclave: (any SecureEnclaveKeyProvider)?206    private let configuration: Configuration207208    private var file: VaultFile?209    private var master: SecretBytes?210    private var recoveredFromPrevious = false211    private var lastActivity: Date212213    public init(214        fileStore: FileStore, keychain: any KeychainStore, secureEnclave: (any SecureEnclaveKeyProvider)? = nil,215        configuration: Configuration = Configuration()216    ) {217        self.fileStore = fileStore218        self.keychain = keychain219        self.secureEnclave = secureEnclave220        self.configuration = configuration221        lastActivity = configuration.now()222    }223224    // MARK: - State225226    /// True when a vault file (or its `.previous` copy) exists.227    public var exists: Bool {228        fileStore.exists(configuration.fileName) || fileStore.previousExists(configuration.fileName)229    }230231    public var isUnlocked: Bool { master != nil }232233    /// The 16-byte vault identifier (not secret).234    public func vaultID() throws -> Bytes {235        try load().vaultID236    }237238    /// Drops the master key; its memory is zeroed as soon as the last reference is gone.239    public func lock() {240        master = nil241    }242243    /// Pure auto-lock decision. A clock that moved backwards locks.244    public static func shouldLock(now: Date, lastActivity: Date, policy: AutoLockPolicy) -> Bool {245        switch policy {246        case .never: return false247        case .immediately: return true248        case .after(let seconds): return now < lastActivity || now.timeIntervalSince(lastActivity) >= seconds249        }250    }251252    /// Marks user activity (every record operation does it as well).253    public func noteActivity() {254        lastActivity = configuration.now()255    }256257    /// Locks when the policy says so. Returns true if the vault is locked afterwards.258    @discardableResult259    public func autoLockIfNeeded(policy: AutoLockPolicy) -> Bool {260        if isUnlocked, Self.shouldLock(now: configuration.now(), lastActivity: lastActivity, policy: policy) { lock() }261        return !isUnlocked262    }263264    // MARK: - Creation and unlocking265266    /// Creates a new vault protected by `password` and leaves it unlocked.267    public func create(password: String) throws {268        guard VaultSelfTest.passed else { throw VaultError.selfTestFailed }269        guard !exists else { throw VaultError.alreadyExists }270        guard !password.isEmpty else { throw VaultError.invalidParameters }271        var key = SystemRandom.bytes(32)272        defer { SecureMemory.zero(&key) }273        var new = VaultFile(274            vaultID: SystemRandom.bytes(16), createdAt: seconds(configuration.now()), epoch: 1, generation: 0,275            password: nil, device: nil, pin: nil, records: [])276        new.password = try makeWrapSlot(277            secret: KeyStretching.passwordBytes(password), master: key, vaultID: new.vaultID, epoch: new.epoch,278            slotType: 1, info: VaultLabels.passwordSlot)279        try persist(new, master: key, scrubPrevious: false)280        master = SecretBytes(key)281        recoveredFromPrevious = false282        noteActivity()283    }284285    public func unlock(password: String) throws {286        try unlockCore { candidate in287            guard let slot = candidate.password else { throw VaultError.corrupted(.malformed) }288            return try self.openWrapSlot(289                slot, secret: KeyStretching.passwordBytes(password), file: candidate, slotType: 1,290                info: VaultLabels.passwordSlot, failure: .wrongPassword)291        }292        // a successful password entry clears the PIN failure counter293        if var state = try? readPINState(), state.failedAttempts != 0 {294            state.failedAttempts = 0295            try? writePINState(state)296        }297    }298299    /// Unlocks with the biometric-protected device key. `prompt` is the reason shown by the system sheet.300    public func unlockWithDevice(prompt: String? = nil) throws {301        try unlockCore { candidate in302            guard let slot = candidate.device else { throw VaultError.deviceSlotNotEnabled }303            var inner = slot.blob304            if slot.usesSecureEnclave {305                guard let enclave = self.secureEnclave, enclave.isAvailable else { throw VaultError.secureEnclaveUnavailable }306                do {307                    inner = try enclave.unwrap(slot.blob)308                } catch {309                    throw VaultError.deviceKeyUnavailable310                }311            }312            guard inner.count == 60 else { throw VaultError.integrityFailure }313            var deviceKey: Bytes314            do throws(StorageError) {315                deviceKey = try self.keychain.get(account: self.account("device-key", candidate.vaultID), prompt: prompt)316            } catch {317                switch error {318                case .authenticationFailed: throw VaultError.deviceAuthenticationFailed319                case .notFound: throw VaultError.deviceKeyUnavailable320                default: throw VaultError.storage(error)321                }322            }323            defer { SecureMemory.zero(&deviceKey) }324            do {325                return try self.configuration.aead.backend.open(326                    key: deviceKey, nonce: Bytes(inner[0..<12]), sealed: Bytes(inner[12...]),327                    associatedData: VaultFile.slotAAD(vaultID: candidate.vaultID, slotType: 2, epoch: candidate.epoch))328            } catch {329                // the Keychain key belongs to another generation of the slot330                throw VaultError.deviceKeyUnavailable331            }332        }333    }334335    /// Unlocks with the PIN. Wrong PINs are counted in the Keychain and delayed according to `PINPolicy.delay`.336    ///337    /// The delay is measured with the monotonic clock of the boot session in which the failure happened338    /// (QYV-SVC-010): setting the date forward does not shorten it. When the elapsed time cannot be measured (the339    /// device restarted, or the state predates this rule) or when the wall clock disagrees with the monotonic clock340    /// while a delay is pending, the full delay starts again from now.341    public func unlock(pin: String) throws {342        let current = try load()343        guard current.pin != nil, var state = try readPINState() else { throw VaultError.pinNotEnabled }344        let now = configuration.now()345        let nowSeconds = seconds(now)346        let instant = configuration.monotonic()347        let wait = PINPolicy.delay(afterFailedAttempts: Int(state.failedAttempts))348        if wait > 0 {349            func restart() throws -> VaultError {350                state.lastFailure = nowSeconds351                state.lastFailureUptime = instant.seconds352                state.bootSession = instant.bootSession353                state.hasMonotonic = true354                try writePINState(state)355                return VaultError.pinLocked(until: Date(timeIntervalSince1970: Double(nowSeconds) + wait))356            }357            // elapsed time is only measurable inside the boot session of the failure358            guard state.hasMonotonic, state.bootSession == instant.bootSession, instant.seconds >= state.lastFailureUptime else { throw try restart() }359            let elapsed = Double(instant.seconds - state.lastFailureUptime)360            if elapsed < wait {361                let wallElapsed = Double(nowSeconds) - Double(state.lastFailure)362                // a date set forward (or backwards) while a delay is pending: the delay starts again363                guard abs(wallElapsed - elapsed) <= PINPolicy.clockDisagreementTolerance else { throw try restart() }364                throw VaultError.pinLocked(until: Date(timeIntervalSince1970: Double(nowSeconds) + (wait - elapsed)))365            }366        }367        // count the attempt before the slow derivation, so that killing the process does not make it free368        state.failedAttempts += 1369        state.lastFailure = nowSeconds370        state.lastFailureUptime = instant.seconds371        state.bootSession = instant.bootSession372        state.hasMonotonic = true373        try writePINState(state)374375        var secret = try pinSecret(pin: pin, vaultID: current.vaultID)376        defer { SecureMemory.zero(&secret) }377        let material = secret378        do {379            try unlockCore { candidate in380                guard let candidateSlot = candidate.pin else { throw VaultError.pinNotEnabled }381                return try self.openWrapSlot(382                    candidateSlot, secret: material, file: candidate, slotType: 3,383                    info: VaultLabels.pinSlot, failure: .wrongPIN(retryAllowedAt: nil))384            }385        } catch VaultError.wrongPIN {386            if state.wipeAfterFailedAttempts != 0, state.failedAttempts >= state.wipeAfterFailedAttempts {387                try destroy()388                throw VaultError.wiped389            }390            let next = PINPolicy.delay(afterFailedAttempts: Int(state.failedAttempts))391            throw VaultError.wrongPIN(retryAllowedAt: next > 0 ? Date(timeIntervalSince1970: Double(nowSeconds) + next) : nil)392        }393        state.failedAttempts = 0394        try writePINState(state)395    }396397    // MARK: - Records398399    /// Seals a new record. `id` and `createdAt` are only supplied when restoring a backup.400    @discardableResult401    public func addRecord(type: RecordType, payload: Bytes, id: UUID? = nil, createdAt: Date? = nil) throws -> UUID {402        var (current, key) = try unlockedState()403        defer { SecureMemory.zero(&key) }404        guard payload.count <= VaultFile.maximumRecordSize else { throw VaultError.invalidParameters }405        let identifier = id ?? UUID()406        guard !current.records.contains(where: { $0.id == identifier.bytes16 }) else { throw VaultError.invalidParameters }407        let now = seconds(configuration.now())408        let created = createdAt.map(seconds) ?? now409        current.records.append(410            try seal(payload, id: identifier.bytes16, type: type, createdAt: created, updatedAt: Swift.max(created, now), file: current, master: key))411        try persist(current, master: key, scrubPrevious: false)412        noteActivity()413        return identifier414    }415416    public func record(_ id: UUID) throws -> VaultRecord {417        var (current, key) = try unlockedState()418        defer { SecureMemory.zero(&key) }419        guard let sealed = current.records.first(where: { $0.id == id.bytes16 }) else { throw VaultError.recordNotFound }420        noteActivity()421        return try open(sealed, file: current, master: key)422    }423424    /// Every record, optionally of one type, in file order.425    public func records(ofType type: RecordType? = nil) throws -> [VaultRecord] {426        var (current, key) = try unlockedState()427        defer { SecureMemory.zero(&key) }428        noteActivity()429        return try current.records.filter { type == nil || $0.type == type }.map { try open($0, file: current, master: key) }430    }431432    /// Non-secret listing; works on a locked vault.433    public func recordSummaries() throws -> [RecordSummary] {434        try load().records.map {435            RecordSummary(436                id: UUID(bytes16: $0.id) ?? UUID(), type: $0.type, createdAt: date($0.createdAt), updatedAt: date($0.updatedAt),437                keyEpoch: $0.epoch, sealedSize: $0.sealed.count)438        }439    }440441    /// Replaces the content of a record (new nonce; identifier, type and creation time are kept).442    public func updateRecord(_ id: UUID, payload: Bytes) throws {443        var (current, key) = try unlockedState()444        defer { SecureMemory.zero(&key) }445        guard payload.count <= VaultFile.maximumRecordSize else { throw VaultError.invalidParameters }446        guard let index = current.records.firstIndex(where: { $0.id == id.bytes16 }) else { throw VaultError.recordNotFound }447        let old = current.records[index]448        current.records[index] = try seal(449            payload, id: old.id, type: old.type, createdAt: old.createdAt, updatedAt: Swift.max(old.createdAt, seconds(configuration.now())),450            file: current, master: key)451        // the replaced content must not survive in the `.previous` copy452        try persist(current, master: key, scrubPrevious: true)453        noteActivity()454    }455456    public func deleteRecord(_ id: UUID) throws {457        var (current, key) = try unlockedState()458        defer { SecureMemory.zero(&key) }459        guard let index = current.records.firstIndex(where: { $0.id == id.bytes16 }) else { throw VaultError.recordNotFound }460        current.records.remove(at: index)461        try persist(current, master: key, scrubPrevious: true)462        noteActivity()463    }464465    // MARK: - Slots466467    /// Re-wraps the master key under a new password (records are untouched). The vault must be unlocked and468    /// `current` must be the present password. The `.previous` copy is overwritten so the old password opens nothing.469    public func changePassword(current: String, new: String) throws {470        var (state, key) = try unlockedState()471        defer { SecureMemory.zero(&key) }472        guard !new.isEmpty else { throw VaultError.invalidParameters }473        guard let slot = state.password else { throw VaultError.corrupted(.malformed) }474        var check = try openWrapSlot(475            slot, secret: KeyStretching.passwordBytes(current), file: state, slotType: 1, info: VaultLabels.passwordSlot, failure: .wrongPassword)476        SecureMemory.zero(&check)477        state.password = try makeWrapSlot(478            secret: KeyStretching.passwordBytes(new), master: key, vaultID: state.vaultID, epoch: state.epoch, slotType: 1,479            info: VaultLabels.passwordSlot)480        try persist(state, master: key, scrubPrevious: true)481    }482483    public var isDeviceSlotEnabled: Bool { (try? load().device) != nil }484    public var isPINEnabled: Bool { (try? load().pin) != nil }485486    /// Adds (or replaces) the device slot: a random key in the Keychain behind biometrics wraps the master key;487    /// with `useSecureEnclave` the result is wrapped a second time by the Secure Enclave key.488    public func enableDeviceSlot(useSecureEnclave: Bool = false) throws {489        var (current, key) = try unlockedState()490        defer { SecureMemory.zero(&key) }491        let (slot, deviceKey) = try makeDeviceSlot(master: key, file: current, useSecureEnclave: useSecureEnclave)492        var keyCopy = deviceKey493        defer { SecureMemory.zero(&keyCopy) }494        try storage { () throws(StorageError) in495            try keychain.set(keyCopy, account: account("device-key", current.vaultID), access: .biometryCurrentSet)496        }497        current.device = slot498        try persist(current, master: key, scrubPrevious: false)499    }500501    public func disableDeviceSlot() throws {502        var (current, key) = try unlockedState()503        defer { SecureMemory.zero(&key) }504        guard current.device != nil else { throw VaultError.deviceSlotNotEnabled }505        current.device = nil506        try persist(current, master: key, scrubPrevious: true)507        try storage { () throws(StorageError) in try keychain.delete(account: account("device-key", current.vaultID)) }508    }509510    /// Adds (or replaces) the PIN slot. The PIN alone is useless without the device-bound Keychain secret.511    public func enablePIN(_ pin: String, policy: PINPolicy = PINPolicy()) throws {512        var (current, key) = try unlockedState()513        defer { SecureMemory.zero(&key) }514        guard pin.count >= PINPolicy.minimumPINLength, (policy.wipeAfterFailedAttempts ?? 1) >= 1 else { throw VaultError.invalidParameters }515        var deviceSecret = SystemRandom.bytes(32)516        defer { SecureMemory.zero(&deviceSecret) }517        let secretCopy = deviceSecret518        try storage { () throws(StorageError) in519            try keychain.set(secretCopy, account: account("pin-secret", current.vaultID), access: .passcodeSetThisDeviceOnly)520        }521        try writePINState(PINState(failedAttempts: 0, lastFailure: 0, wipeAfterFailedAttempts: UInt32(policy.wipeAfterFailedAttempts ?? 0)))522        var secret = try pinSecret(pin: pin, vaultID: current.vaultID)523        defer { SecureMemory.zero(&secret) }524        current.pin = try makeWrapSlot(525            secret: secret, master: key, vaultID: current.vaultID, epoch: current.epoch, slotType: 3, info: VaultLabels.pinSlot)526        try persist(current, master: key, scrubPrevious: true)527    }528529    public func disablePIN() throws {530        var (current, key) = try unlockedState()531        defer { SecureMemory.zero(&key) }532        guard current.pin != nil else { throw VaultError.pinNotEnabled }533        current.pin = nil534        try persist(current, master: key, scrubPrevious: true)535        try removePINMaterial(vaultID: current.vaultID)536    }537538    // MARK: - Key rotation539540    /// Replaces the master key: new key epoch, every record re-encrypted, every slot re-wrapped.541    ///542    /// The password is required (its slot cannot be re-wrapped without it). A PIN slot is re-wrapped when `pin`543    /// is supplied and removed otherwise. The device slot receives a new Keychain key. The `.previous` copy is544    /// overwritten, so nothing on disk remains readable with the old master key.545    public func rotateMasterKey(password: String, pin: String? = nil) throws -> KeyRotationResult {546        var (old, oldKey) = try unlockedState()547        defer { SecureMemory.zero(&oldKey) }548        guard let passwordSlot = old.password else { throw VaultError.corrupted(.malformed) }549        var check = try openWrapSlot(550            passwordSlot, secret: KeyStretching.passwordBytes(password), file: old, slotType: 1, info: VaultLabels.passwordSlot,551            failure: .wrongPassword)552        SecureMemory.zero(&check)553        if let pin, let pinSlot = old.pin {554            var secret = try pinSecret(pin: pin, vaultID: old.vaultID)555            defer { SecureMemory.zero(&secret) }556            var pinCheck = try openWrapSlot(557                pinSlot, secret: secret, file: old, slotType: 3, info: VaultLabels.pinSlot, failure: .wrongPIN(retryAllowedAt: nil))558            SecureMemory.zero(&pinCheck)559        }560561        var newKey = SystemRandom.bytes(32)562        defer { SecureMemory.zero(&newKey) }563        var new = old564        new.epoch = old.epoch + 1565        new.records = []566        for sealed in old.records {567            let plain = try open(sealed, file: old, master: oldKey)568            var payload = plain.payload569            defer { SecureMemory.zero(&payload) }570            new.records.append(571                try seal(payload, id: sealed.id, type: sealed.type, createdAt: sealed.createdAt, updatedAt: sealed.updatedAt, file: new, master: newKey))572        }573        new.password = try makeWrapSlot(574            secret: KeyStretching.passwordBytes(password), master: newKey, vaultID: new.vaultID, epoch: new.epoch, slotType: 1,575            info: VaultLabels.passwordSlot)576        var newDeviceKey: Bytes?577        if let device = old.device {578            let (slot, deviceKey) = try makeDeviceSlot(master: newKey, file: new, useSecureEnclave: device.usesSecureEnclave)579            new.device = slot580            newDeviceKey = deviceKey581        }582        var pinKept = old.pin == nil583        if old.pin != nil, let pin {584            var secret = try pinSecret(pin: pin, vaultID: old.vaultID)585            defer { SecureMemory.zero(&secret) }586            new.pin = try makeWrapSlot(secret: secret, master: newKey, vaultID: new.vaultID, epoch: new.epoch, slotType: 3, info: VaultLabels.pinSlot)587            pinKept = true588        } else {589            new.pin = nil590        }591592        try persist(new, master: newKey, scrubPrevious: true)593        master = SecretBytes(newKey)594        if var deviceKey = newDeviceKey {595            defer { SecureMemory.zero(&deviceKey) }596            let copy = deviceKey597            try storage { () throws(StorageError) in598                try keychain.set(copy, account: account("device-key", new.vaultID), access: .biometryCurrentSet)599            }600        }601        if old.pin != nil, new.pin == nil { try removePINMaterial(vaultID: new.vaultID) }602        return KeyRotationResult(newKeyEpoch: new.epoch, recordsReencrypted: new.records.count, pinSlotKept: old.pin == nil ? true : pinKept)603    }604605    // MARK: - Integrity, report, destruction606607    /// Re-reads the file from disk, verifies its checksum and HMAC, and opens every record.608    public func verifyIntegrity() throws -> IntegrityReport {609        var (current, key) = try unlockedState()610        defer { SecureMemory.zero(&key) }611        let parsed = try VaultFile.parse(try storage { () throws(StorageError) in try fileStore.read(configuration.fileName) })612        guard verifyMAC(parsed, master: key), parsed.file == current else { throw VaultError.integrityFailure }613        for sealed in current.records {614            guard sealed.epoch == current.epoch else { throw VaultError.integrityFailure }615            var plain = try open(sealed, file: current, master: key).payload616            SecureMemory.zero(&plain)617        }618        return IntegrityReport(recordsVerified: current.records.count, generation: current.generation)619    }620621    /// Algorithms, parameters and counters of this vault. Contains no secret; available while locked.622    public func report() throws -> VaultReport {623        let current = try load()624        let state = try? readPINState()625        var counts: [String: Int] = [:]626        for r in current.records { counts[r.type.name, default: 0] += 1 }627        let construction = "HKDF-SHA256(Argon2id ‖ PBKDF2-HMAC-SHA512)"628        return VaultReport(629            formatVersion: Int(VaultFile.version), vaultID: current.vaultID.hex, createdAt: date(current.createdAt),630            keyEpoch: current.epoch, generation: current.generation, isUnlocked: isUnlocked,631            recordEncryption: "AES-256-GCM", sealingBackend: configuration.aead.backend.name, nonceBits: 96, masterKeyBits: 256,632            subkeyDerivation: "HKDF-SHA256", fileAuthentication: "HMAC-SHA256",633            passwordSlot: current.password.map { .init(construction: construction, parameters: $0.kdf) },634            pinSlot: current.pin.map { .init(construction: construction, parameters: $0.kdf) },635            deviceSlotEnabled: current.device != nil, deviceSlotUsesSecureEnclave: current.device?.usesSecureEnclave ?? false,636            pinFailedAttempts: current.pin == nil ? nil : state.map { Int($0.failedAttempts) },637            pinWipeAfterFailedAttempts: state.flatMap { $0.wipeAfterFailedAttempts == 0 ? nil : Int($0.wipeAfterFailedAttempts) },638            recordCounts: counts, totalRecords: current.records.count, recoveredFromPreviousCopy: recoveredFromPrevious,639            selfTestPassed: VaultSelfTest.passed)640    }641642    /// Erases the vault from this device: file, `.previous` copy and Keychain material. Irreversible.643    public func destroy() throws {644        let id = (try? load())?.vaultID645        lock()646        file = nil647        try storage { () throws(StorageError) in try fileStore.remove(configuration.fileName) }648        if let id {649            try storage { () throws(StorageError) in try keychain.delete(account: account("device-key", id)) }650            try removePINMaterial(vaultID: id)651        }652    }653654    // MARK: - Internals: loading and unlocking655656    private func storage<T>(_ body: () throws(StorageError) -> T) throws -> T {657        do {658            return try body()659        } catch {660            throw VaultError.storage(error)661        }662    }663664    private func seconds(_ date: Date) -> UInt64 {665        VaultTime.seconds(date)666    }667668    private func date(_ seconds: UInt64) -> Date {669        Date(timeIntervalSince1970: TimeInterval(seconds))670    }671672    private func account(_ kind: String, _ vaultID: Bytes) -> String {673        "vault.\(vaultID.hex).\(kind)"674    }675676    private func readParsed(previous: Bool) throws -> VaultFile.Parsed {677        let bytes: Bytes678        do throws(StorageError) {679            bytes = try previous ? fileStore.readPrevious(configuration.fileName) : fileStore.read(configuration.fileName)680        } catch {681            throw error == .notFound ? VaultError.notFound : VaultError.storage(error)682        }683        return try VaultFile.parse(bytes)684    }685686    /// The in-memory file, read from disk on first use. A damaged current file falls back to `.previous`.687    @discardableResult688    private func load() throws -> VaultFile {689        if let file { return file }690        do {691            let parsed = try readParsed(previous: false)692            file = parsed.file693            recoveredFromPrevious = false694            return parsed.file695        } catch let primary as VaultError {696            switch primary {697            case .corrupted, .notFound:698                guard let fallback = try? readParsed(previous: true) else { throw primary }699                file = fallback.file700                recoveredFromPrevious = true701                return fallback.file702            default:703                throw primary704            }705        }706    }707708    private func verifyMAC(_ parsed: VaultFile.Parsed, master: Bytes) -> Bool {709        var macKey = VaultFile.subkey(master: master, vaultID: parsed.file.vaultID, epoch: parsed.file.epoch, label: VaultLabels.fileMAC)710        defer { SecureMemory.zero(&macKey) }711        return ConstantTime.equal(SystemCrypto.hmacSHA256(key: macKey, message: parsed.authenticated), parsed.mac)712    }713714    /// Common unlock path. `unwrap` extracts the master key from one candidate file; the file HMAC is then verified715    /// before the key is accepted. Only damage (never a wrong credential) makes it try the `.previous` copy.716    private func unlockCore(_ unwrap: (VaultFile) throws -> Bytes) throws {717        guard VaultSelfTest.passed else { throw VaultError.selfTestFailed }718        file = nil719        try load()720        var candidates: [VaultFile.Parsed] = []721        if !recoveredFromPrevious, let current = try? readParsed(previous: false) { candidates.append(current) }722        let usingPreviousOnly = candidates.isEmpty723        if let previous = try? readParsed(previous: true) { candidates.append(previous) }724        guard !candidates.isEmpty else { throw VaultError.notFound }725726        for (index, candidate) in candidates.enumerated() {727            var key: Bytes728            do {729                key = try unwrap(candidate.file)730            } catch {731                // a credential that fails on the current file is final; on the fallback copy report the damage instead732                if index == 0 { throw error }733                throw VaultError.integrityFailure734            }735            defer { SecureMemory.zero(&key) }736            guard verifyMAC(candidate, master: key) else { continue }737            file = candidate.file738            master = SecretBytes(key)739            if index > 0 || usingPreviousOnly {740                recoveredFromPrevious = true741                // repair the damaged current file without touching the good `.previous` copy742                try persist(candidate.file, master: key, scrubPrevious: false, keepPrevious: false)743            }744            noteActivity()745            return746        }747        throw VaultError.integrityFailure748    }749750    private func unlockedState() throws -> (VaultFile, Bytes) {751        guard let master, let file else { throw VaultError.locked }752        return (file, master.copyBytes())753    }754755    /// Writes `new` as the next generation and makes it the in-memory state.756    private func persist(_ new: VaultFile, master: Bytes, scrubPrevious: Bool, keepPrevious: Bool = true) throws {757        var next = new758        next.generation = new.generation + 1759        var macKey = VaultFile.subkey(master: master, vaultID: next.vaultID, epoch: next.epoch, label: VaultLabels.fileMAC)760        defer { SecureMemory.zero(&macKey) }761        let bytes = next.encoded(macKey: macKey)762        try storage { () throws(StorageError) in763            try fileStore.write(bytes, to: configuration.fileName, keepPrevious: keepPrevious)764            // a second write turns `.previous` into a copy of the new file: no older slot or record stays on disk765            if scrubPrevious { try fileStore.write(bytes, to: configuration.fileName, keepPrevious: true) }766        }767        file = next768    }769770    // MARK: - Internals: sealing771772    private func nonce() -> Bytes { SystemRandom.bytes(12) }773774    private func seal(775        _ payload: Bytes, id: Bytes, type: RecordType, createdAt: UInt64, updatedAt: UInt64, file: VaultFile, master: Bytes776    ) throws -> VaultFile.SealedRecord {777        var key = VaultFile.subkey(master: master, vaultID: file.vaultID, epoch: file.epoch, label: VaultLabels.records)778        defer { SecureMemory.zero(&key) }779        let n = nonce()780        let sealed = try configuration.aead.backend.seal(781            key: key, nonce: n, plaintext: payload,782            associatedData: VaultFile.recordAAD(vaultID: file.vaultID, recordID: id, type: type, createdAt: createdAt, epoch: file.epoch))783        return VaultFile.SealedRecord(id: id, type: type, createdAt: createdAt, updatedAt: updatedAt, epoch: file.epoch, nonce: n, sealed: sealed)784    }785786    private func open(_ sealed: VaultFile.SealedRecord, file: VaultFile, master: Bytes) throws -> VaultRecord {787        var key = VaultFile.subkey(master: master, vaultID: file.vaultID, epoch: sealed.epoch, label: VaultLabels.records)788        defer { SecureMemory.zero(&key) }789        let payload = try configuration.aead.backend.open(790            key: key, nonce: sealed.nonce, sealed: sealed.sealed,791            associatedData: VaultFile.recordAAD(792                vaultID: file.vaultID, recordID: sealed.id, type: sealed.type, createdAt: sealed.createdAt, epoch: sealed.epoch))793        guard let id = UUID(bytes16: sealed.id) else { throw VaultError.integrityFailure }794        return VaultRecord(id: id, type: sealed.type, createdAt: date(sealed.createdAt), updatedAt: date(sealed.updatedAt), payload: payload)795    }796797    private func makeWrapSlot(secret: Bytes, master: Bytes, vaultID: Bytes, epoch: UInt32, slotType: UInt8, info: String) throws -> VaultFile.WrapSlot {798        guard configuration.kdf.isWithin(configuration.kdfCeiling) else { throw VaultError.invalidParameters }799        let argonSalt = SystemRandom.bytes(KeyStretching.saltSize), pbkdfSalt = SystemRandom.bytes(KeyStretching.saltSize)800        var kek = try KeyStretching.deriveKey(801            secret: secret, argon2Salt: argonSalt, pbkdf2Salt: pbkdfSalt, parameters: configuration.kdf, info: info)802        defer { SecureMemory.zero(&kek) }803        let n = nonce()804        let wrapped = try configuration.aead.backend.seal(805            key: kek, nonce: n, plaintext: master, associatedData: VaultFile.slotAAD(vaultID: vaultID, slotType: slotType, epoch: epoch))806        return VaultFile.WrapSlot(kdf: configuration.kdf, argon2Salt: argonSalt, pbkdf2Salt: pbkdfSalt, nonce: n, wrapped: wrapped)807    }808809    private func openWrapSlot(810        _ slot: VaultFile.WrapSlot, secret: Bytes, file: VaultFile, slotType: UInt8, info: String, failure: VaultError811    ) throws -> Bytes {812        // The cost comes from the file and is paid before the credential can be checked: a header asking for more than813        // this device accepts is damage or forgery, not a slot to open (QYV-SVC-012).814        guard slot.kdf.isWithin(configuration.kdfCeiling) else { throw VaultError.corrupted(.malformed) }815        var kek = try KeyStretching.deriveKey(816            secret: secret, argon2Salt: slot.argon2Salt, pbkdf2Salt: slot.pbkdf2Salt, parameters: slot.kdf, info: info)817        defer { SecureMemory.zero(&kek) }818        do {819            let key = try configuration.aead.backend.open(820                key: kek, nonce: slot.nonce, sealed: slot.wrapped,821                associatedData: VaultFile.slotAAD(vaultID: file.vaultID, slotType: slotType, epoch: file.epoch))822            guard key.count == 32 else { throw VaultError.integrityFailure }823            return key824        } catch {825            throw failure826        }827    }828829    private func makeDeviceSlot(master: Bytes, file: VaultFile, useSecureEnclave: Bool) throws -> (VaultFile.DeviceSlot, Bytes) {830        let deviceKey = SystemRandom.bytes(32)831        let n = nonce()832        var blob = n + (try configuration.aead.backend.seal(833            key: deviceKey, nonce: n, plaintext: master, associatedData: VaultFile.slotAAD(vaultID: file.vaultID, slotType: 2, epoch: file.epoch)))834        if useSecureEnclave {835            guard let secureEnclave, secureEnclave.isAvailable else { throw VaultError.secureEnclaveUnavailable }836            let inner = blob837            blob = try storage { () throws(StorageError) in try secureEnclave.wrap(inner) }838        }839        return (VaultFile.DeviceSlot(usesSecureEnclave: useSecureEnclave, blob: blob), deviceKey)840    }841842    // MARK: - Internals: PIN state843844    /// Keychain item `vault.<vault id hex>.pin-state`:845    /// version (u8 = 2) ‖ failedAttempts (u32) ‖ lastFailure (u64, wall-clock seconds) ‖ wipeAfterFailedAttempts (u32, 0 = never)846    /// ‖ lastFailureUptime (u64, monotonic seconds since boot) ‖ boot session length (u8, 0 or 16) ‖ boot session.847    /// Version 1 (17 bytes, written before QYV-SVC-010) stops after `wipeAfterFailedAttempts`; it is read as a state848    /// without monotonic time, so a pending delay restarts in full.849    /// Living in the Keychain, the counter survives a replaced or restored vault file.850    private struct PINState {851        var failedAttempts: UInt32852        var lastFailure: UInt64853        var wipeAfterFailedAttempts: UInt32854        var lastFailureUptime: UInt64 = 0855        var bootSession: Bytes = []856        var hasMonotonic = false857    }858859    private func readPINState() throws -> PINState? {860        guard let id = (try? load())?.vaultID else { return nil }861        let bytes: Bytes862        do throws(StorageError) {863            bytes = try keychain.get(account: account("pin-state", id), prompt: nil)864        } catch {865            if error == .notFound { return nil }866            throw VaultError.storage(error)867        }868        var r = ByteReader(bytes)869        guard let version = try? r.u8(), version == 1 || version == 2, let failed = try? r.u32(), let last = try? r.u64(), let wipe = try? r.u32()870        else { return nil }871        if version == 1 {872            guard r.remaining == 0 else { return nil }873            return PINState(failedAttempts: failed, lastFailure: last, wipeAfterFailedAttempts: wipe)874        }875        guard let uptime = try? r.u64(), let length = try? r.u8(), length == 0 || length == 16, let boot = try? r.raw(Int(length)), r.remaining == 0876        else { return nil }877        return PINState(failedAttempts: failed, lastFailure: last, wipeAfterFailedAttempts: wipe, lastFailureUptime: uptime, bootSession: boot,878                        hasMonotonic: true)879    }880881    private func writePINState(_ state: PINState) throws {882        let id = try load().vaultID883        var w = ByteWriter()884        w.u8(2)885        w.u32(state.failedAttempts)886        w.u64(state.lastFailure)887        w.u32(state.wipeAfterFailedAttempts)888        w.u64(state.lastFailureUptime)889        let boot = state.bootSession.count == 16 ? state.bootSession : []890        w.u8(UInt8(boot.count))891        w.raw(boot)892        let bytes = w.bytes893        try storage { () throws(StorageError) in894            try keychain.set(bytes, account: account("pin-state", id), access: .passcodeSetThisDeviceOnly)895        }896    }897898    /// u16 length ‖ NFKD-UTF-8(PIN) ‖ device secret.899    private func pinSecret(pin: String, vaultID: Bytes) throws -> Bytes {900        let pinBytes = KeyStretching.passwordBytes(pin)901        guard pinBytes.count <= 0xffff else { throw VaultError.invalidParameters }902        var deviceSecret: Bytes903        do throws(StorageError) {904            deviceSecret = try keychain.get(account: account("pin-secret", vaultID), prompt: nil)905        } catch {906            throw error == .notFound ? VaultError.pinNotEnabled : VaultError.storage(error)907        }908        defer { SecureMemory.zero(&deviceSecret) }909        var w = ByteWriter()910        w.prefixed16(pinBytes)911        w.raw(deviceSecret)912        return w.bytes913    }914915    private func removePINMaterial(vaultID: Bytes) throws {916        try storage { () throws(StorageError) in917            try keychain.delete(account: account("pin-secret", vaultID))918            try keychain.delete(account: account("pin-state", vaultID))919        }920    }921922    // MARK: - Test support923924    /// A copy of the master key, for the test target only (`@testable import`).925    func masterKeyCopyForTesting() -> Bytes? {926        master?.copyBytes()927    }928}929
Files main
Menu

Theme