SPB Git

Repository Public

BackupFile.swift 18.0 KB 390 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraRecovery/BackupFile.swift8// Module           : Qyvora Recovery9// 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 QyvoraStorage44import QyvoraVault4546/// Errors of the backup format. No case carries secret data.47public enum BackupError: Error, Equatable, Sendable {48    /// The file ends before its declared structure does.49    case truncated50    /// Not a QYVORA backup.51    case badMagic52    /// A backup written by a newer format.53    case unsupportedVersion(UInt16)54    /// The trailing SHA-256 checksum does not match: the file was damaged in storage or transit.55    case checksumMismatch56    /// The checksum matches but a field is out of range or inconsistent.57    case malformed58    /// AES-GCM authentication failed: wrong password, or header or ciphertext modified.59    case authenticationFailed60    /// The backup carries a signature that does not verify.61    case invalidSignature62    /// A signature was required but the backup is not signed, or no verifier was supplied for a signed backup.63    case signatureRequired64    /// The backup is validly signed, but not by the expected signer.65    case unexpectedSigner66    /// A decrypted record does not match its digest.67    case recordIntegrity68    /// Empty password, KDF parameters out of range, too many or too large records.69    case invalidParameters70    case kdfFailure71    case signingFailed72    case vault(VaultError)73}7475/// The readable part of a backup: available without the password.76public struct BackupHeader: Sendable, Equatable {77    public let formatVersion: Int78    public let createdAt: Date79    /// Identifier of the vault the records came from (16 bytes).80    public let vaultID: Bytes81    public let kdf: KDFParameters82    public let recordCount: Int83    /// Public encoding of the signer (binary `PublicIdentity`), when the backup is signed.84    public let signerEncoding: Bytes?85    public var isSigned: Bool { signerEncoding != nil }86}8788/// A decrypted backup.89public struct BackupContents: Sendable, Equatable {90    public let header: BackupHeader91    public let records: [VaultRecord]92    /// True when the backup was signed and the signature was verified.93    public let signatureVerified: Bool94}9596/// "QYVORA Backup v1", file extension `.qyvora`: every vault record, re-encrypted under a key derived from a97/// backup password that is independent of the vault password.98///99/// All integers are unsigned big-endian. Times are whole seconds since 1970-01-01 UTC.100///101///     file     = magic ‖ version ‖ headerLength ‖ header ‖ nonce ‖ sealedLength ‖ sealed ‖ signatureLength ‖ signature ‖ checksum102///     magic    = "QYVORABK"                                   8 bytes (ASCII)103///     version  = 0x0001                                       u16104///     headerLength (u32) ‖ header105///     nonce                                                   12 bytes, random106///     sealedLength (u32) ‖ sealed = AES-256-GCM ciphertext ‖ 16-byte tag107///     signatureLength (u32) ‖ signature                       0 = unsigned; otherwise a binary IdentitySignature108///     checksum = SHA-256(every preceding byte)                32 bytes109///110///     header   = createdAt (u64) ‖ vaultID (16)111///                ‖ argon2MemoryKiB (u32) ‖ argon2Iterations (u32) ‖ argon2Parallelism (u32) ‖ pbkdf2Iterations (u32)112///                ‖ argon2Salt (16) ‖ pbkdf2Salt (16) ‖ recordCount (u32)113///                ‖ signerLength (u32) ‖ signer               0 = unsigned; otherwise a binary PublicIdentity114///115///     key      = KeyStretching(NFKD-UTF-8(password), argon2Salt, pbkdf2Salt, parameters, info = "qyvora/v1/backup")116///                (HKDF-SHA256 over Argon2id ‖ PBKDF2-HMAC-SHA512: the same combiner as the vault, with its own salts)117///     associated data = magic ‖ version ‖ headerLength ‖ header118///119///     plaintext = recordCount (u32) ‖ record*120///     record    = recordID (16) ‖ recordType (u8) ‖ createdAt (u64) ‖ updatedAt (u64) ‖ payloadLength (u32) ‖ payload121///                 ‖ SHA-256(recordID ‖ recordType ‖ createdAt ‖ updatedAt ‖ payloadLength ‖ payload)   32 bytes122///123///     signature = detached signature, purpose "backup", over every byte from magic through sealed124///                 (present if and only if the header names a signer)125///126/// Reading order: structure and checksum, then the signature when present, then key derivation and decryption,127/// then the digest of every record. The checksum only detects accidental damage; authenticity comes from AES-GCM128/// (password holders) and from the optional signature (a specific identity).129public enum BackupFile {130    public static let magic = Bytes("QYVORABK".utf8)131    public static let version: UInt16 = 1132    public static let fileExtension = "qyvora"133    public static let signaturePurpose = "backup"134    public static let maximumFileSize = 256 << 20135    public static let maximumRecordCount = 100_000136137    // MARK: Writing138139    /// Builds a backup of `records`. Use a strong password: the file is meant to leave the device.140    public static func create(141        records: [VaultRecord], vaultID: Bytes, password: String, kdf: KDFParameters = .standard, signer: (any DetachedSigner)? = nil,142        createdAt: Date = Date()143    ) throws(BackupError) -> Bytes {144        guard !password.isEmpty, vaultID.count == 16, kdf.isWithinLimits, records.count <= maximumRecordCount else { throw .invalidParameters }145        let argon2Salt = SystemRandom.bytes(KeyStretching.saltSize), pbkdf2Salt = SystemRandom.bytes(KeyStretching.saltSize)146        let signerEncoding = signer?.signerEncoding ?? []147        guard signer == nil || !signerEncoding.isEmpty, signerEncoding.count <= 1 << 16 else { throw .invalidParameters }148149        var header = ByteWriter()150        header.u64(VaultTime.seconds(createdAt))151        header.raw(vaultID)152        kdf.encode(into: &header)153        header.raw(argon2Salt)154        header.raw(pbkdf2Salt)155        header.u32(UInt32(records.count))156        header.prefixed32(signerEncoding)157158        var out = ByteWriter()159        out.raw(magic)160        out.u16(version)161        out.prefixed32(header.bytes)162        let associatedData = out.bytes163164        var plain = ByteWriter()165        plain.u32(UInt32(records.count))166        for record in records {167            let body = recordBody(record)168            plain.raw(body)169            plain.raw(SystemCrypto.sha256(body))170        }171        var plaintext = plain.bytes172        defer { SecureMemory.zero(&plaintext) }173        guard plaintext.count <= maximumFileSize else { throw .invalidParameters }174175        var key = try deriveKey(password: password, argon2Salt: argon2Salt, pbkdf2Salt: pbkdf2Salt, kdf: kdf)176        defer { SecureMemory.zero(&key) }177        let nonce = SystemRandom.bytes(12)178        guard let sealed = try? SystemAEAD().seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: associatedData) else {179            throw .invalidParameters180        }181        out.raw(nonce)182        out.prefixed32(sealed)183        if let signer {184            guard let signature = try? signer.detachedSignature(over: out.bytes, purpose: signaturePurpose), !signature.isEmpty else {185                throw .signingFailed186            }187            out.prefixed32(signature)188        } else {189            out.u32(0)190        }191        out.raw(SystemCrypto.sha256(out.bytes))192        return out.bytes193    }194195    /// Backs up every record of an unlocked vault.196    public static func export(197        from vault: Vault, password: String, kdf: KDFParameters = .standard, signer: (any DetachedSigner)? = nil, createdAt: Date = Date()198    ) async throws(BackupError) -> Bytes {199        let records: [VaultRecord]200        let vaultID: Bytes201        do {202            records = try await vault.records()203            vaultID = try await vault.vaultID()204        } catch let error as VaultError {205            throw .vault(error)206        } catch {207            throw .malformed208        }209        return try create(records: records, vaultID: vaultID, password: password, kdf: kdf, signer: signer, createdAt: createdAt)210    }211212    // MARK: Reading213214    struct Parsed {215        var header: BackupHeader216        var argon2Salt: Bytes217        var pbkdf2Salt: Bytes218        var associatedData: Bytes219        var nonce: Bytes220        var sealed: Bytes221        var signedBytes: Bytes222        var signature: Bytes223    }224225    static func parse(_ bytes: Bytes) throws(BackupError) -> Parsed {226        guard bytes.count <= maximumFileSize else { throw .malformed }227        guard bytes.count >= magic.count + 2 else { throw .truncated }228        guard Bytes(bytes[0..<magic.count]) == magic else { throw .badMagic }229        let v = UInt16(bytes[8]) << 8 | UInt16(bytes[9])230        guard v == version else { throw .unsupportedVersion(v) }231        guard bytes.count >= magic.count + 2 + 4 + 12 + 4 + 16 + 4 + 32 else { throw .truncated }232        let checksumStart = bytes.count - 32233        guard ConstantTime.equal(SystemCrypto.sha256(Bytes(bytes[0..<checksumStart])), Bytes(bytes[checksumStart...])) else {234            throw .checksumMismatch235        }236        do {237            var r = ByteReader(Bytes(bytes[10..<checksumStart]))238            let headerBytes = try r.prefixed32(max: 1 << 17)239            let associatedData = Bytes(bytes[0..<(10 + 4 + headerBytes.count)])240            let nonce = try r.raw(12)241            let sealed = try r.prefixed32(max: maximumFileSize)242            let signedBytes = Bytes(bytes[0..<(10 + r.offset)])243            let signature = try r.prefixed32(max: 1 << 17)244            try r.finish()245246            var h = ByteReader(headerBytes)247            let createdAt = try h.u64()248            let vaultID = try h.raw(16)249            let kdf = try KDFParameters(from: &h)250            let argon2Salt = try h.raw(16), pbkdf2Salt = try h.raw(16)251            let recordCount = try h.u32()252            let signer = try h.prefixed32(max: 1 << 16)253            try h.finish()254            guard kdf.isWithinLimits, Int(recordCount) <= maximumRecordCount, sealed.count >= 16 + 4, signer.isEmpty == signature.isEmpty else {255                throw BackupError.malformed256            }257            return Parsed(258                header: BackupHeader(259                    formatVersion: Int(v), createdAt: Date(timeIntervalSince1970: TimeInterval(createdAt)), vaultID: vaultID, kdf: kdf,260                    recordCount: Int(recordCount), signerEncoding: signer.isEmpty ? nil : signer),261                argon2Salt: argon2Salt, pbkdf2Salt: pbkdf2Salt, associatedData: associatedData, nonce: nonce, sealed: sealed,262                signedBytes: signedBytes, signature: signature)263        } catch let error as BackupError {264            throw error265        } catch ByteReaderError.truncated {266            throw .truncated267        } catch {268            throw .malformed269        }270    }271272    /// Reads the header without the password (structure and checksum are verified, nothing else).273    public static func inspect(_ bytes: Bytes) throws(BackupError) -> BackupHeader {274        try parse(bytes).header275    }276277    /// Verifies and decrypts a backup.278    ///279    /// - `verifier`: checks the signature of a signed backup (pass `IdentityDetachedVerifier()` from QyvoraIdentity).280    ///   A signed backup opened without a verifier throws `signatureRequired`: a signature is never silently ignored.281    /// - `expectedSignerFingerprint`: when set, the backup must be signed by exactly this signer.282    /// - `requireSignature`: refuse unsigned backups.283    public static func open(284        _ bytes: Bytes, password: String, verifier: (any DetachedVerifier)? = nil, expectedSignerFingerprint: Bytes? = nil,285        requireSignature: Bool = false286    ) throws(BackupError) -> BackupContents {287        let parsed = try parse(bytes)288        var verified = false289        if let signer = parsed.header.signerEncoding {290            guard let verifier else { throw .signatureRequired }291            guard verifier.isValid(signature: parsed.signature, over: parsed.signedBytes, signerEncoding: signer, purpose: signaturePurpose) else {292                throw .invalidSignature293            }294            if let expectedSignerFingerprint {295                guard let actual = verifier.signerFingerprint(of: signer), ConstantTime.equal(actual, expectedSignerFingerprint) else {296                    throw .unexpectedSigner297                }298            }299            verified = true300        } else if requireSignature || expectedSignerFingerprint != nil {301            throw .signatureRequired302        }303304        guard !password.isEmpty else { throw .invalidParameters }305        var key = try deriveKey(password: password, argon2Salt: parsed.argon2Salt, pbkdf2Salt: parsed.pbkdf2Salt, kdf: parsed.header.kdf)306        defer { SecureMemory.zero(&key) }307        guard var plaintext = try? SystemAEAD().open(key: key, nonce: parsed.nonce, sealed: parsed.sealed, associatedData: parsed.associatedData)308        else { throw .authenticationFailed }309        defer { SecureMemory.zero(&plaintext) }310311        var records: [VaultRecord] = []312        do {313            var r = ByteReader(plaintext)314            let count = Int(try r.u32())315            guard count == parsed.header.recordCount else { throw BackupError.malformed }316            var seen = Set<UUID>()317            for _ in 0..<count {318                let start = r.offset319                let idBytes = try r.raw(16)320                let typeByte = try r.u8()321                let createdAt = try r.u64(), updatedAt = try r.u64()322                let payload = try r.prefixed32(max: plaintext.count)323                let body = Bytes(plaintext[start..<r.offset])324                guard ConstantTime.equal(SystemCrypto.sha256(body), try r.raw(32)) else { throw BackupError.recordIntegrity }325                guard let id = UUID(bytes16: idBytes), let type = RecordType(rawValue: typeByte), seen.insert(id).inserted else {326                    throw BackupError.malformed327                }328                records.append(329                    VaultRecord(330                        id: id, type: type, createdAt: Date(timeIntervalSince1970: TimeInterval(createdAt)),331                        updatedAt: Date(timeIntervalSince1970: TimeInterval(updatedAt)), payload: payload))332            }333            try r.finish()334        } catch let error as BackupError {335            throw error336        } catch {337            throw .malformed338        }339        return BackupContents(header: parsed.header, records: records, signatureVerified: verified)340    }341342    /// Opens the backup and imports every record into `vault`, which must be unlocked — normally a vault just created343    /// on the new device with `Vault.create(password:)`. Record identifiers and creation times are preserved.344    /// Nothing is imported unless the whole backup verifies. Returns what was restored.345    @discardableResult346    public static func restore(347        _ bytes: Bytes, password: String, into vault: Vault, verifier: (any DetachedVerifier)? = nil, expectedSignerFingerprint: Bytes? = nil,348        requireSignature: Bool = false349    ) async throws(BackupError) -> BackupContents {350        let contents = try open(351            bytes, password: password, verifier: verifier, expectedSignerFingerprint: expectedSignerFingerprint, requireSignature: requireSignature)352        do {353            let existing = Set(try await vault.recordSummaries().map(\.id))354            guard await vault.isUnlocked else { throw VaultError.locked }355            guard contents.records.allSatisfy({ !existing.contains($0.id) }) else { throw VaultError.invalidParameters }356            for record in contents.records {357                try await vault.addRecord(type: record.type, payload: record.payload, id: record.id, createdAt: record.createdAt)358            }359        } catch let error as VaultError {360            throw .vault(error)361        } catch {362            throw .malformed363        }364        return contents365    }366367    // MARK: Internals368369    private static func recordBody(_ record: VaultRecord) -> Bytes {370        var w = ByteWriter()371        w.raw(record.id.bytes16)372        w.u8(record.type.rawValue)373        w.u64(VaultTime.seconds(record.createdAt))374        w.u64(VaultTime.seconds(record.updatedAt))375        w.prefixed32(record.payload)376        return w.bytes377    }378379    private static func deriveKey(password: String, argon2Salt: Bytes, pbkdf2Salt: Bytes, kdf: KDFParameters) throws(BackupError) -> Bytes {380        var secret = KeyStretching.passwordBytes(password)381        defer { SecureMemory.zero(&secret) }382        do {383            return try KeyStretching.deriveKey(384                secret: secret, argon2Salt: argon2Salt, pbkdf2Salt: pbkdf2Salt, parameters: kdf, info: VaultLabels.backup)385        } catch {386            throw error == .invalidParameters ? .invalidParameters : .kdfFailure387        }388    }389}390
Files main
Menu

Theme