Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,19 @@ struct VaultKeyMaterial: Equatable {
/// `vmk` (ready to use immediately, e.g. to encrypt the first imported file),
/// and the `recoveryKey` that MUST be shown to the user exactly once - this
/// module does not retain or persist it anywhere.
///
/// `vmk` is deliberately `var`, not `let`: callers that fail after this is
/// created (see `VaultStore.create`'s catch block) need to scrub it in
/// place. `Data` is a copy-on-write value type, so zeroing a *copy* (e.g.
/// `var c = newVault.vmk; c.secureZero()`) only zeroes the copy's freshly
/// forked buffer, leaving this property's own storage — the only other
/// reference keeping the original buffer alive — untouched. A `let` here
/// would make that mistake the only way to scrub it. Mirrors Android's
/// `NewVault.vmk: ByteArray`, whose reference semantics don't have this
/// footgun (`newVault.vmk.fill(0)` mutates the one true backing array).
struct NewVault {
let material: VaultKeyMaterial
let vmk: Data
var vmk: Data
let recoveryKey: Data
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import Foundation

/// On-disk wire format for `vault.json`. Field names deliberately mirror
/// Android's `VaultConfigDto` (`core/vaultstore`). Unlike Android,
/// failed-PIN throttle state (`failedAttempts`/`lastAttemptEpochMillis`)
/// lives in its own file (`UnlockAttemptThrottleStore`, #301) rather than
/// folded into this one — no behavior difference, just a file split #301
/// already established before this issue started. No legacy-format concern
/// here (unlike `VaultManifest`'s custom decoder): this is a brand-new type
/// with no pre-existing vault.json files to stay compatible with, so a
/// plain synthesized `Codable` is enough.
private struct VaultConfigDto: Codable {
let formatVersion: Int
let keystoreKeyAlias: String
let argon2SaltB64: String
let argon2MemoryKiB: Int
let argon2Iterations: Int
let argon2Parallelism: Int
let keystoreWrapCiphertextB64: String
let recoveryWrappedVmkNonceB64: String
let recoveryWrappedVmkCiphertextB64: String
}

/// Decoded, ready-to-use form of a vault's persisted config — what
/// `VaultConfig.read` returns. Base64/DTO plumbing stays internal to this
/// file; callers get already-typed `Data`/`WrappedBlob`/`WrappedKey`/
/// `Argon2Params` values directly, unlike Android's `VaultConfigDto` plus
/// separate `argon2ParamsOf`/`keystoreWrapOf`/`recoveryWrappedVmkOf`
/// helper-function trio.
struct VaultConfigData {
let keystoreKeyAlias: String
let argon2Salt: Data
let argon2Params: Argon2Params
let keystoreWrap: WrappedBlob
let wrappedVmkByRecovery: WrappedKey
}

extension WrappedKey {
/// Concatenates `nonce` + `ciphertext` into one blob, for passing
/// through `HardwareKeyWrap.wrap` — the fixed `VaultFormat.nonceSizeBytes`
/// prefix makes it losslessly reversible via `init(serialized:)`. Mirrors
/// Android's `WrappedKey.toBytes()`/`bytesToWrappedKey()` (`VaultConfig.kt`).
var serialized: Data { nonce + ciphertext }

init(serialized data: Data) {
self.init(nonce: data.prefix(VaultFormat.nonceSizeBytes), ciphertext: data.dropFirst(VaultFormat.nonceSizeBytes))
}
}

/// Everything needed to unlock a vault, persisted as JSON in the vault's own
/// directory (`vault.json`). Swift port of Android's `VaultConfig` object.
///
/// **Deliberately does NOT store the KEK-wrapped VMK's nonce/ciphertext a
/// second time in the clear.** That blob only exists as the plaintext
/// recovered by unwrapping `keystoreWrap` (see `VaultStore.unlockWithPin`).
/// Storing it a second time outside the Secure Enclave wrap would let an
/// attacker who copies this file skip the hardware wrap entirely and go
/// straight to offline Argon2id brute-force against a 4-digit PIN — exactly
/// what the Secure Enclave layer (#303) exists to prevent. Same reasoning
/// Android's `VaultConfigDto` doc comment documents for its own schema.
///
/// `recoveryWrappedVmkNonceB64`/`recoveryWrappedVmkCiphertextB64` are fine to
/// store in the clear, by contrast: protected by the recovery key's own 256
/// bits of entropy, not by being hidden, and must be reachable without the
/// Secure Enclave layer so they can rescue a vault whose Secure Enclave key
/// is lost.
enum VaultConfig {

private static let fileName = "vault.json"

static func path(vaultDir: URL) -> URL {
vaultDir.appendingPathComponent(fileName)
}

static func exists(vaultDir: URL) -> Bool {
FileManager.default.fileExists(atPath: path(vaultDir: vaultDir).path)
}

static func write(
vaultDir: URL,
keystoreKeyAlias: String,
argon2Salt: Data,
argon2Params: Argon2Params,
keystoreWrap: WrappedBlob,
wrappedVmkByRecovery: WrappedKey
) throws {
let dto = VaultConfigDto(
formatVersion: 1,
keystoreKeyAlias: keystoreKeyAlias,
argon2SaltB64: argon2Salt.base64EncodedString(),
argon2MemoryKiB: argon2Params.memoryKiB,
argon2Iterations: argon2Params.iterations,
argon2Parallelism: argon2Params.parallelism,
keystoreWrapCiphertextB64: keystoreWrap.ciphertext.base64EncodedString(),
recoveryWrappedVmkNonceB64: wrappedVmkByRecovery.nonce.base64EncodedString(),
recoveryWrappedVmkCiphertextB64: wrappedVmkByRecovery.ciphertext.base64EncodedString()
)
try FileManager.default.createDirectory(at: vaultDir, withIntermediateDirectories: true)
let data = try JSONEncoder().encode(dto)
// .atomic: writes to an auxiliary file then renames into place, same
// write-to-temp-then-rename guarantee as VaultRegistry.writeAll (#301)
// and Android's own File.renameTo-based writeAtomically.
try data.write(to: path(vaultDir: vaultDir), options: .atomic)
}

/// - Throws: a decoding/`Data(contentsOf:)` error if `vault.json` is
/// missing or malformed, or `VaultCryptoError.malformedHeader` if a
/// base64 field is corrupt.
static func read(vaultDir: URL) throws -> VaultConfigData {
let data = try Data(contentsOf: path(vaultDir: vaultDir))
let dto = try JSONDecoder().decode(VaultConfigDto.self, from: data)

guard let salt = Data(base64Encoded: dto.argon2SaltB64),
let keystoreCiphertext = Data(base64Encoded: dto.keystoreWrapCiphertextB64),
let recoveryNonce = Data(base64Encoded: dto.recoveryWrappedVmkNonceB64),
let recoveryCiphertext = Data(base64Encoded: dto.recoveryWrappedVmkCiphertextB64)
else {
throw VaultCryptoError.malformedHeader("vault.json contains invalid base64")
}

return VaultConfigData(
keystoreKeyAlias: dto.keystoreKeyAlias,
argon2Salt: salt,
argon2Params: Argon2Params(
memoryKiB: dto.argon2MemoryKiB,
iterations: dto.argon2Iterations,
parallelism: dto.argon2Parallelism
),
keystoreWrap: WrappedBlob(ciphertext: keystoreCiphertext),
wrappedVmkByRecovery: WrappedKey(nonce: recoveryNonce, ciphertext: recoveryCiphertext)
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import Foundation
#if canImport(UIKit)
import UIKit
#endif

#if canImport(UIKit)
/// Locks every open vault the instant the app leaves the foreground —
/// `UIApplication.willResignActiveNotification`, per the design scoped in
/// #201's split: immediate, not waiting for full backgrounding, so a
/// transient interruption (an incoming call, Control Center, the app
/// switcher) re-locks too, not just a full app-switch. Mirrors Android's
/// `VaultSessionManager` registering a `ProcessLifecycleOwner` `onStop`
/// observer in its own `init`.
///
/// A separate, plain (non-actor) type rather than folding this into
/// `VaultSessionManager` itself: `NotificationCenter` observer registration
/// is a UIKit/notification-delivery concern, not a vault-state concern —
/// keeping it here means `VaultSessionManager`'s own tests never need to
/// simulate app-lifecycle notifications to exercise its actual create/
/// unlock/lock logic, and this type's own test can simulate exactly one
/// notification and assert the real, observable effect.
final class VaultForegroundLockObserver {

private let sessionManager: VaultSessionManager
private var token: NSObjectProtocol?

init(sessionManager: VaultSessionManager, notificationCenter: NotificationCenter = .default) {
self.sessionManager = sessionManager
token = notificationCenter.addObserver(
forName: UIApplication.willResignActiveNotification,
object: nil,
queue: nil
) { [sessionManager] _ in
Task { await sessionManager.lockAll() }
}
}

deinit {
if let token {
NotificationCenter.default.removeObserver(token)
}
}
}
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import Foundation

/// Outcome of `VaultSessionManager.createVault`. Mirrors Android's
/// `CreateVaultResult` sealed class.
enum CreateVaultResult: Equatable {
/// `recoveryKey` — show this to the user exactly once, see `VaultStore.create`.
case success(id: String, recoveryKey: Data)
/// No Secure Enclave on this device — a 4-digit PIN isn't defensible
/// here. The caller should require a longer passphrase instead of
/// retrying with the same PIN, or refuse to create the vault.
case hardwareUnavailable
}

/// App-wide entry point for Encrypted Vaults: owns the `VaultRegistry`
/// (which vaults exist) plus one `VaultStore` instance per vault the user
/// has touched this session (locked or unlocked). Swift port of Android's
/// `VaultSessionManager`.
///
/// An `actor`, not a class wrapping a manual lock: actor isolation gives the
/// same "single-writer boundary across every vault operation" guarantee
/// Android gets from wrapping every method in one shared `Mutex`, enforced
/// by the compiler rather than by convention — simpler than a per-vault lock
/// map, and cheap here: these are all user-tap-driven, one-at-a-time
/// operations, not a hot path, matching `VaultStore`'s own doc comment,
/// which expects exactly this kind of single-writer wrapper.
///
/// Deliberately does NOT itself observe app-lifecycle notifications — see
/// `VaultForegroundLockObserver`, a separate type specifically so this
/// actor's own tests never need to simulate `UIApplication` notifications to
/// exercise its actual vault logic.
actor VaultSessionManager {

private let rootDir: URL
private let keyWrapFactory: HardwareKeyWrapFactory
private var stores: [String: VaultStore] = [:]

init(rootDir: URL, keyWrapFactory: HardwareKeyWrapFactory) {
self.rootDir = rootDir
self.keyWrapFactory = keyWrapFactory
}

func listVaults() -> [VaultRegistryEntry] {
VaultRegistry.list(baseDir: rootDir)
}

func isUnlocked(_ id: String) -> Bool {
stores[id]?.isUnlocked ?? false
}

/// Creates a brand-new vault, registers it, and leaves it unlocked.
func createVault(displayName: String, pin: [UInt8]) throws -> CreateVaultResult {
let id = UUID().uuidString
let store = storeFor(id: id)
do {
let recoveryKey = try store.create(pin: pin)
try VaultRegistry.add(
baseDir: rootDir,
entry: VaultRegistryEntry(id: id, displayName: displayName, createdAtEpochMillis: Int64(Date().timeIntervalSince1970 * 1000))
)
return .success(id: id, recoveryKey: recoveryKey)
} catch HardwareKeyWrapError.secureEnclaveUnavailable {
// Nothing was registered yet, and VaultStore.create's own catch
// block already deleted the half-created vault directory - just
// drop the in-memory reference so a retry starts clean.
stores.removeValue(forKey: id)
return .hardwareUnavailable
}
}

func unlockWithPin(id: String, pin: [UInt8]) throws -> UnlockOutcome {
try storeFor(id: id).unlockWithPin(pin)
}

func unlockWithRecoveryKey(id: String, recoveryKey: Data) throws -> UnlockOutcome {
try storeFor(id: id).unlockWithRecoveryKey(recoveryKey)
}

func lock(_ id: String) {
stores[id]?.lock()
}

/// Locks every vault touched this session — called on every
/// `willResignActive` transition by `VaultForegroundLockObserver`.
func lockAll() {
stores.values.forEach { $0.lock() }
}

/// The unlocked `VaultStore` for `id`, for callers that already checked
/// `isUnlocked`.
func requireUnlocked(_ id: String) -> VaultStore {
guard let store = stores[id], store.isUnlocked else {
preconditionFailure("Vault \(id) is not unlocked")
}
return store
}

private func storeFor(id: String) -> VaultStore {
if let existing = stores[id] { return existing }
let store = VaultStore(
vaultDir: VaultRegistry.vaultDir(baseDir: rootDir, id: id),
keystoreKeyAlias: keystoreAlias(for: id),
keyWrapFactory: keyWrapFactory
)
stores[id] = store
return store
}

private func keystoreAlias(for id: String) -> String { "libravault_vault_\(id)" }
}
Loading