From 022cee8f5827d67757ec8ea5c2c9e1e513d175d8 Mon Sep 17 00:00:00 2001 From: Paul Flynn Date: Wed, 25 Nov 2026 19:26:22 -0500 Subject: [PATCH 1/3] perf: remove CryptoSwift, add streaming file TDF I/O, and fix hot-path bottlenecks --- CLAUDE.md | 2 +- OpenTDFKit/BinaryParser.swift | 15 +- OpenTDFKit/KASRewrapClient.swift | 212 +++++---- OpenTDFKit/KASService.swift | 81 ++-- OpenTDFKit/KeyStore.swift | 57 ++- OpenTDFKit/NanoTDF.swift | 15 +- OpenTDFKit/NanoTDFCollection.swift | 18 +- OpenTDFKit/NanoTDFCollectionDecryptor.swift | 42 +- OpenTDFKit/PublicKeyStore.swift | 21 +- OpenTDFKit/TDF/StreamingTDFCrypto.swift | 148 +++++- OpenTDFKit/TDF/StrictJSON.swift | 49 +- OpenTDFKit/TDF/TDFCBORContainer.swift | 53 +-- OpenTDFKit/TDF/TDFCrypto.swift | 319 +++++++------ OpenTDFKit/TDF/TDFJSONContainer.swift | 55 +-- OpenTDFKit/TDF/TDFKAS.swift | 5 +- OpenTDFKit/TDF/TDFProcessor.swift | 439 ++++++++++++------ OpenTDFKitTests/GCMEncryptionTests.swift | 8 +- OpenTDFKitTests/StreamingTDFCryptoTests.swift | 111 +++++ OpenTDFKitTests/TDFTests.swift | 42 ++ Package.resolved | 11 +- Package.swift | 2 - 21 files changed, 1102 insertions(+), 603 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 848971e..2bdc2e3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -321,7 +321,7 @@ The KAS rewrap protocol enables secure key distribution with policy enforcement: - **Algorithm**: AES-256-GCM - **Supported Tag Sizes**: 64, 96, 104, 112, 120, 128 bits - 128-bit tags use CryptoKit (optimized) - - Other tag sizes use CryptoSwift + - Other tag sizes use CommonCrypto AES-CTR + CryptoKit GCM tag verification - **IV Size**: 12 bytes (96 bits) - **Nonce Handling**: 3-byte NanoTDF nonce + 9-byte zero padding diff --git a/OpenTDFKit/BinaryParser.swift b/OpenTDFKit/BinaryParser.swift index 32704c8..c03c19c 100644 --- a/OpenTDFKit/BinaryParser.swift +++ b/OpenTDFKit/BinaryParser.swift @@ -106,10 +106,8 @@ public class BinaryParser { else { throw ParsingError.invalidPolicy } - let plaintextCiphertextLengthData = contentLengthData.prefix(2) - - let bytes = Array(plaintextCiphertextLengthData) - let contentLength = (UInt16(bytes[0]) << 8) | UInt16(bytes[1]) + let i0 = contentLengthData.startIndex + let contentLength = (UInt16(contentLengthData[i0]) << 8) | UInt16(contentLengthData[contentLengthData.index(after: i0)]) // Note 3.4.2.3.2 Body for Embedded Policy states Minimum Length is 1 if contentLength == 0 { @@ -265,11 +263,10 @@ public class BinaryParser { guard let lengthData = read(length: FieldSize.payloadLengthSize), lengthData.count == FieldSize.payloadLengthSize else { throw ParsingError.invalidFormat } - let b = Array(lengthData) - let byte1 = UInt32(b[0]) << 16 - let byte2 = UInt32(b[1]) << 8 - let byte3 = UInt32(b[2]) - let length: UInt32 = byte1 | byte2 | byte3 + let i0 = lengthData.startIndex + let i1 = lengthData.index(after: i0) + let i2 = lengthData.index(after: i1) + let length: UInt32 = (UInt32(lengthData[i0]) << 16) | (UInt32(lengthData[i1]) << 8) | UInt32(lengthData[i2]) // IV nonce guard let iv = read(length: FieldSize.payloadIvSize) diff --git a/OpenTDFKit/KASRewrapClient.swift b/OpenTDFKit/KASRewrapClient.swift index d590a19..3eed81e 100644 --- a/OpenTDFKit/KASRewrapClient.swift +++ b/OpenTDFKit/KASRewrapClient.swift @@ -2,18 +2,6 @@ import CryptoKit import Darwin import Foundation -/// URLSession task delegate that refuses HTTP redirects. The KAS rewrap target -/// is an RPC endpoint that must never redirect; following a 3xx could re-issue -/// the bearer-carrying request to an unvalidated host. -final class NoRedirectDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable { - func urlSession(_: URLSession, task _: URLSessionTask, - willPerformHTTPRedirection _: HTTPURLResponse, newRequest _: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) - { - completionHandler(nil) - } -} - /// Sends the HTTP requests a `KASRewrapClient` makes (rewrap and public-key /// fetch). Inject one to apply an app's own destination or TLS policy. /// @@ -350,11 +338,11 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { /// HKDF salt for Standard TDF EC session unwrap — matches go SDK `tdfSalt()`: /// `SHA256("TDF")`. - public static var standardTDFSessionSalt: Data { + public static let standardTDFSessionSalt: Data = { var hasher = SHA256() hasher.update(data: Data("TDF".utf8)) return Data(hasher.finalize()) - } + }() /// Flatten rewrap metadata for deny/fail diagnostics when no `error` string is present. private static func rewrapDenyReason(_ metadata: [String: RewrapMetadataValue]?) -> String? { @@ -446,10 +434,20 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { // MARK: - Properties + /// Pre-parsed components of `kasIdentityURL` so `matchesKasURL` does not re-parse + /// and re-normalize the client's own URL on every KAO in bulk rewrap calls. + private struct ParsedKasIdentity: Sendable { + let scheme: String + let host: String + let port: Int + let normalizedPath: String + } + let endpoints: KasEndpoints /// KAS identity url for the request-body KeyAccessObject when the NanoTDF /// header locator is unavailable (fallback only). private let kasIdentityURL: String + private let parsedKasIdentity: ParsedKasIdentity? let oauthToken: String let transport: any KASRewrapTransport let signingKey: P256.Signing.PrivateKey @@ -501,7 +499,21 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { now: @escaping @Sendable () -> Date) throws { endpoints = try KasEndpoints.from(configuration) - kasIdentityURL = configuration.kas?.uri ?? "" + let identity = configuration.kas?.uri ?? "" + kasIdentityURL = identity + if let url = URL(string: identity), + let scheme = url.scheme?.lowercased(), + let host = url.host?.lowercased() + { + parsedKasIdentity = ParsedKasIdentity( + scheme: scheme, + host: host, + port: Self.effectivePort(for: url), + normalizedPath: Self.normalizedKasPath(url), + ) + } else { + parsedKasIdentity = nil + } self.oauthToken = oauthToken self.transport = transport self.signingKey = signingKey ?? P256.Signing.PrivateKey() @@ -734,7 +746,7 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { ) let wrapper = StandardKeyAccessObjectWrapper( - keyAccessObjectId: String(format: "kao-%d", index), + keyAccessObjectId: "kao-\(index)", keyAccessObject: accessObject, ) wrappers.append(wrapper) @@ -809,7 +821,19 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { } do { - let (sessionPublicKey, _) = try Self.validateEcPublicKeyPEM(sessionPEM) + let sessionPublicKey = try Self.validateEcPublicKeyPEM(sessionPEM).key + guard case let .p256(p256SessionKey) = sessionPublicKey else { + throw KASRewrapError.invalidEcPublicKey("Expected P-256 session public key") + } + // Derive the session KEK once for the entire response instead of per share. + let sessionKEK = try clientPrivateKey + .sharedSecretFromKeyAgreement(with: p256SessionKey) + .hkdfDerivedSymmetricKey( + using: SHA256.self, + salt: Self.standardTDFSessionSalt, + sharedInfo: Data(), + outputByteCount: 32, + ) // Validate `kao-` prefix, bounds, and sort numerically (not lexicographically). let indexedResults: [(index: Int, wrappedKey: Data)] = try result.wrappedKeys.map { objectID, wrappedKey in guard objectID.hasPrefix("kao-"), @@ -822,12 +846,7 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { } return try indexedResults.sorted { $0.index < $1.index }.map { entry in let sid = entries[entry.index].sid - let key = try Self.unwrapKey( - wrappedKey: entry.wrappedKey, - sessionPublicKey: sessionPublicKey, - clientPrivateKey: clientPrivateKey.rawRepresentation, - salt: Self.standardTDFSessionSalt, - ) + let key = try Self.unwrapKey(wrappedKey: entry.wrappedKey, sessionKEK: sessionKEK) return TDFKeyShare(sid: sid, key: key) } } catch let error as KASRewrapError { @@ -1119,17 +1138,16 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { /// (case-insensitive), effective port, and normalized path. A platform KAS and /// owner KASs share one host, so the path decides. private func matchesKasURL(_ otherURLString: String) -> Bool { - guard let otherURL = URL(string: otherURLString), let kasURL = URL(string: kasIdentityURL), - let baseScheme = kasURL.scheme?.lowercased(), + guard let base = parsedKasIdentity, + let otherURL = URL(string: otherURLString), let otherScheme = otherURL.scheme?.lowercased(), - let baseHost = kasURL.host?.lowercased(), let otherHost = otherURL.host?.lowercased(), - baseScheme == otherScheme, baseHost == otherHost + base.scheme == otherScheme, base.host == otherHost else { return false } - return effectivePort(for: kasURL) == effectivePort(for: otherURL) - && Self.normalizedKasPath(kasURL) == Self.normalizedKasPath(otherURL) + return base.port == Self.effectivePort(for: otherURL) + && base.normalizedPath == Self.normalizedKasPath(otherURL) } /// A KAS URL's path for matching: percent-encoded unreserved characters @@ -1149,30 +1167,61 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { /// and upper-cases the hex of the rest, which stay encoded (an encoded `/` /// is not a path separator). static func normalizedPercentEncoding(_ path: String) -> String { - var output = "" - var bytes = Array(path.utf8)[...] - while let byte = bytes.first { - bytes = bytes.dropFirst() - guard byte == UInt8(ascii: "%"), bytes.count >= 2, - let value = UInt8(String(decoding: bytes.prefix(2), as: UTF8.self), radix: 16) - else { - output.unicodeScalars.append(Unicode.Scalar(byte)) - continue + let hexUpper: [UInt8] = [ + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, + ] + @inline(__always) + func hexNibble(_ byte: UInt8) -> UInt8? { + switch byte { + case 0x30 ... 0x39: byte - 0x30 + case 0x41 ... 0x46: byte - 0x41 + 10 + case 0x61 ... 0x66: byte - 0x61 + 10 + default: nil } - bytes = bytes.dropFirst(2) - let scalar = Unicode.Scalar(value) - if CharacterSet(charactersIn: "-._~").contains(scalar) || (scalar.isASCII && scalar.properties.isAlphabetic) - || ("0" ... "9").contains(scalar) + } + @inline(__always) + func isUnreserved(_ byte: UInt8) -> Bool { + switch byte { + case 0x41 ... 0x5A, 0x61 ... 0x7A, 0x30 ... 0x39, 0x2D, 0x2E, 0x5F, 0x7E: + true + default: + false + } + } + + let utf8 = Array(path.utf8) + var out = [UInt8]() + out.reserveCapacity(utf8.count) + var i = 0 + while i < utf8.count { + let byte = utf8[i] + if byte == 0x25, i + 2 < utf8.count, + let hi = hexNibble(utf8[i + 1]), + let lo = hexNibble(utf8[i + 2]) { - output.unicodeScalars.append(scalar) + let decoded = (hi << 4) | lo + if isUnreserved(decoded) { + out.append(decoded) + } else { + out.append(0x25) + out.append(hexUpper[Int(hi)]) + out.append(hexUpper[Int(lo)]) + } + i += 3 } else { - output += String(format: "%%%02X", value) + out.append(byte) + i += 1 } } - return output + return String(decoding: out, as: UTF8.self) } func effectivePort(for url: URL) -> Int { + Self.effectivePort(for: url) + } + + static func effectivePort(for url: URL) -> Int { if let explicitPort = url.port { return explicitPort } @@ -1251,7 +1300,13 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { sharedInfo: Data(), outputByteCount: 32, ) + return try unwrapKey(wrappedKey: wrappedKey, sessionKEK: symmetricKey) + } + private static func unwrapKey( + wrappedKey: Data, + sessionKEK: SymmetricKey, + ) throws -> SymmetricKey { // Decrypt the wrapped key // The wrapped key format from platform is: nonce (12 bytes) + ciphertext + tag (16 bytes) // The platform KAS always uses 128-bit (16-byte) tags, so CryptoKit works here @@ -1261,7 +1316,7 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { // Use the SealedBox combined initializer which expects nonce+ciphertext+tag let sealedBox = try AES.GCM.SealedBox(combined: wrappedKey) - var decryptedKey = try AES.GCM.open(sealedBox, using: symmetricKey) + var decryptedKey = try AES.GCM.open(sealedBox, using: sessionKEK) defer { decryptedKey.secureZero() } @@ -1320,35 +1375,16 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { case .secp384r1: "ES384" case .secp521r1: "ES512" } - - let header = ["alg": alg, "typ": "JWT"] - let headerJSON = try JSONSerialization.data(withJSONObject: header) - let headerBase64 = headerJSON.base64URLEncodedString() - - let requestBodyString = String(data: requestBody, encoding: .utf8) ?? "" - let claims: [String: Any] = [ - "requestBody": requestBodyString, - "iat": issuedAt, - "exp": expiresAt, - ] - let claimsJSON = try JSONSerialization.data(withJSONObject: claims) - let claimsBase64 = claimsJSON.base64URLEncodedString() - - let signingInput = "\(headerBase64).\(claimsBase64)".data(using: .utf8)! - let rawSignature: Data - switch curve { - case .secp256r1: - let key = try P256.Signing.PrivateKey(rawRepresentation: privateKeyData) - rawSignature = try key.signature(for: signingInput).rawRepresentation - case .secp384r1: - let key = try P384.Signing.PrivateKey(rawRepresentation: privateKeyData) - rawSignature = try key.signature(for: signingInput).rawRepresentation - case .secp521r1: - let key = try P521.Signing.PrivateKey(rawRepresentation: privateKeyData) - rawSignature = try key.signature(for: signingInput).rawRepresentation - } - let signatureBase64 = rawSignature.base64URLEncodedString() - return "\(headerBase64).\(claimsBase64).\(signatureBase64)" + return try createSignedJWT(alg: alg, requestBody: requestBody, issuedAt: issuedAt, expiresAt: expiresAt) { signingInput in + switch curve { + case .secp256r1: + try P256.Signing.PrivateKey(rawRepresentation: privateKeyData).signature(for: signingInput).rawRepresentation + case .secp384r1: + try P384.Signing.PrivateKey(rawRepresentation: privateKeyData).signature(for: signingInput).rawRepresentation + case .secp521r1: + try P521.Signing.PrivateKey(rawRepresentation: privateKeyData).signature(for: signingInput).rawRepresentation + } + } } /// Create a signed JWT using ES256 algorithm @@ -1364,12 +1400,21 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { issuedAt: Int, expiresAt: Int, ) throws -> String { - // Create header with ES256 algorithm - let header = ["alg": "ES256", "typ": "JWT"] - let headerJSON = try JSONSerialization.data(withJSONObject: header) + try createSignedJWT(alg: "ES256", requestBody: requestBody, issuedAt: issuedAt, expiresAt: expiresAt) { signingInput in + try signingKey.signature(for: signingInput).rawRepresentation + } + } + + private func createSignedJWT( + alg: String, + requestBody: Data, + issuedAt: Int, + expiresAt: Int, + sign: (Data) throws -> Data, + ) throws -> String { + let headerJSON = try JSONSerialization.data(withJSONObject: ["alg": alg, "typ": "JWT"]) let headerBase64 = headerJSON.base64URLEncodedString() - // Create claims with the request body and required timestamps let requestBodyString = String(data: requestBody, encoding: .utf8) ?? "" let claims: [String: Any] = [ "requestBody": requestBodyString, @@ -1379,11 +1424,8 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { let claimsJSON = try JSONSerialization.data(withJSONObject: claims) let claimsBase64 = claimsJSON.base64URLEncodedString() - // Create signature over header.payload - let signingInput = "\(headerBase64).\(claimsBase64)".data(using: .utf8)! - let signature = try signingKey.signature(for: signingInput) - let signatureBase64 = signature.rawRepresentation.base64URLEncodedString() - + let signingInput = Data("\(headerBase64).\(claimsBase64)".utf8) + let signatureBase64 = try sign(signingInput).base64URLEncodedString() return "\(headerBase64).\(claimsBase64).\(signatureBase64)" } } @@ -1491,6 +1533,6 @@ extension Data { } func hexEncodedString() -> String { - map { String(format: "%02x", $0) }.joined() + hexString } } diff --git a/OpenTDFKit/KASService.swift b/OpenTDFKit/KASService.swift index 4cac556..c5dd8a5 100644 --- a/OpenTDFKit/KASService.swift +++ b/OpenTDFKit/KASService.swift @@ -229,35 +229,40 @@ public actor KASService { privateKeyData: Data, policyBody: Data? = nil, policyBinding: Data? = nil, + precomputedPrimaryKey: SymmetricKey? = nil, ) async throws -> (rewrappedKey: Data, newKeyPair: StoredKeyPair) { - // 1. Derive shared secret using the client's ephemeral public key and KAS private key - let sharedSecret: SharedSecret - - switch keyStore.curve { - case .secp256r1: - let privateKey = try P256.KeyAgreement.PrivateKey(rawRepresentation: privateKeyData) - let publicKey = try P256.KeyAgreement.PublicKey(compressedRepresentation: ephemeralPublicKey) - sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey) - - case .secp384r1: - let privateKey = try P384.KeyAgreement.PrivateKey(rawRepresentation: privateKeyData) - let publicKey = try P384.KeyAgreement.PublicKey(compressedRepresentation: ephemeralPublicKey) - sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey) + // 1-2. Derive symmetric key for decryption (using v12 salt) unless already computed by caller + let primaryKey: SymmetricKey + if let precomputedPrimaryKey { + primaryKey = precomputedPrimaryKey + } else { + let sharedSecret: SharedSecret + + switch keyStore.curve { + case .secp256r1: + let privateKey = try P256.KeyAgreement.PrivateKey(rawRepresentation: privateKeyData) + let publicKey = try P256.KeyAgreement.PublicKey(compressedRepresentation: ephemeralPublicKey) + sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey) + + case .secp384r1: + let privateKey = try P384.KeyAgreement.PrivateKey(rawRepresentation: privateKeyData) + let publicKey = try P384.KeyAgreement.PublicKey(compressedRepresentation: ephemeralPublicKey) + sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey) + + case .secp521r1: + let privateKey = try P521.KeyAgreement.PrivateKey(rawRepresentation: privateKeyData) + let publicKey = try P521.KeyAgreement.PublicKey(compressedRepresentation: ephemeralPublicKey) + sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey) + } - case .secp521r1: - let privateKey = try P521.KeyAgreement.PrivateKey(rawRepresentation: privateKeyData) - let publicKey = try P521.KeyAgreement.PublicKey(compressedRepresentation: ephemeralPublicKey) - sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey) + primaryKey = sharedSecret.hkdfDerivedSymmetricKey( + using: SHA256.self, + salt: CryptoConstants.hkdfSaltV12, + sharedInfo: Data(), // Empty per spec section 4 + outputByteCount: 32, + ) } - // 2. Derive symmetric key for decryption using v12 salt only - let primaryKey = sharedSecret.hkdfDerivedSymmetricKey( - using: SHA256.self, - salt: CryptoConstants.hkdfSaltV12, - sharedInfo: Data(), // Empty per spec section 4 - outputByteCount: 32, - ) - // 2b. Verify policy binding when provided (if either is set, both must be present and valid) if policyBody != nil || policyBinding != nil { guard let body = policyBody, let binding = policyBinding else { @@ -328,13 +333,10 @@ public actor KASService { let newSealedBox = try AES.GCM.seal(decryptedKey, using: newSymmetricKey, nonce: newNonce) // 8. Combine the new ephemeral public key with the encrypted data - var result = Data() - result.append(newKeyPair.publicKey) - - // Add nonce, ciphertext, and tag separately for compatibility with our test format - var nonceBytes = Data() - newNonce.withUnsafeBytes { nonceBytes.append(contentsOf: $0) } - result.append(nonceBytes) + let newPublicKey = newKeyPair.publicKey + var result = Data(capacity: newPublicKey.count + 12 + newSealedBox.ciphertext.count + newSealedBox.tag.count) + result.append(newPublicKey) + newNonce.withUnsafeBytes { result.append(contentsOf: $0) } result.append(newSealedBox.ciphertext) result.append(newSealedBox.tag) @@ -413,6 +415,7 @@ public actor KASService { ephemeralPublicKey: header.ephemeralPublicKey, encryptedKey: encryptedKey, privateKeyData: privateKeyData, + precomputedPrimaryKey: symmetricKey, ) return rewrappedKey } @@ -436,19 +439,7 @@ public actor KASService { return false } let expectedTag = Data(fullTag.prefix(policyBinding.count)) - return constantTimeEquals(policyBinding, expectedTag) - } - - /// Compares two byte collections in constant time to mitigate timing attacks. - /// Returns `true` if the collections are equal, `false` otherwise. - /// The length comparison is intentionally not constant-time: the tag length is public. - private func constantTimeEquals(_ lhs: Data, _ rhs: Data) -> Bool { - guard lhs.count == rhs.count else { return false } - var result: UInt8 = 0 - for (a, b) in zip(lhs, rhs) { - result |= a ^ b - } - return result == 0 + return CryptoHelper.constantTimeEquals(policyBinding, expectedTag) } /// Atomically processes a one-time key access request, verifies the policy binding, diff --git a/OpenTDFKit/KeyStore.swift b/OpenTDFKit/KeyStore.swift index 0a5e198..b563f55 100644 --- a/OpenTDFKit/KeyStore.swift +++ b/OpenTDFKit/KeyStore.swift @@ -55,6 +55,14 @@ public struct StoredKeyPair: Sendable { } } + /// Appends `publicKey || privateKey` directly from contiguous zero-on-deinit storage + /// without allocating intermediate `Data` copies of the private key. + func appendSerializedBytes(to destination: inout Data) { + storage.bytes.withUnsafeBytes { buffer in + destination.append(contentsOf: buffer) + } + } + init(publicKey: Data, privateKey: Data) { storage = SecureKeyPairStorage(publicKey: publicKey, privateKey: privateKey) publicKeyLength = publicKey.count @@ -80,9 +88,9 @@ public struct EphemeralKeyPair: Sendable { public actor KeyStore { public let curve: Curve - public var keyPairs: [KeyPairIdentifier: StoredKeyPair] + public private(set) var keyPairs: [KeyPairIdentifier: StoredKeyPair] /// Track total memory used - public var totalBytesStored: Int = 0 + public private(set) var totalBytesStored: Int = 0 public init(curve: Curve, capacity: Int = 1000) { self.curve = curve @@ -133,25 +141,35 @@ public actor KeyStore { /// Batch generation method public func generateAndStoreKeyPairs(count: Int) async throws { + guard count > 0 else { return } // Capture immutable state before leaving the actor context let curveSnapshot = curve - // Pre-allocate space for results + // Chunk work across available CPU cores rather than spawning `count` individual tasks. + let workerCount = min(count, max(1, ProcessInfo.processInfo.activeProcessorCount)) + let baseChunk = count / workerCount + let remainder = count % workerCount + var tempPairs: [(KeyPairIdentifier, StoredKeyPair)] = [] tempPairs.reserveCapacity(count) - // Generate keys concurrently in detached tasks outside the actor - try await withThrowingTaskGroup(of: StoredKeyPair.self) { group in - for _ in 0 ..< count { + try await withThrowingTaskGroup(of: [(KeyPairIdentifier, StoredKeyPair)].self) { group in + for worker in 0 ..< workerCount { + let batchSize = baseChunk + (worker < remainder ? 1 : 0) group.addTask { - KeyStore.makeKeyPair(curve: curveSnapshot) + var localPairs: [(KeyPairIdentifier, StoredKeyPair)] = [] + localPairs.reserveCapacity(batchSize) + for _ in 0 ..< batchSize { + let keyPair = KeyStore.makeKeyPair(curve: curveSnapshot) + let identifier = KeyPairIdentifier(publicKey: keyPair.publicKey) + localPairs.append((identifier, keyPair)) + } + return localPairs } } - // Collect all generated key pairs - for try await keyPair in group { - let identifier = KeyPairIdentifier(publicKey: keyPair.publicKey) - tempPairs.append((identifier, keyPair)) + for try await batch in group { + tempPairs.append(contentsOf: batch) } } @@ -215,10 +233,9 @@ public actor KeyStore { withUnsafeBytes(of: count.bigEndian) { data.append(contentsOf: $0) } // Append the big-endian representation of the key pair count to the data. - // Store key pairs - no need for length prefixes since sizes are fixed per curve + // Store key pairs directly from contiguous storage (no unzeroed intermediate copies) for keyPair in keyPairs.values { - data.append(keyPair.publicKey) - data.append(keyPair.privateKey) + keyPair.appendSerializedBytes(to: &data) } return data @@ -506,7 +523,17 @@ public enum KeyStoreError: Error, Equatable { /// Helper extension for Data to hex string (for debugging/errors) public extension Data { var hexString: String { - map { String(format: "%02x", $0) }.joined() + let hexDigits: [UInt8] = [ + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, + ] + var utf8 = [UInt8]() + utf8.reserveCapacity(count * 2) + for byte in self { + utf8.append(hexDigits[Int(byte >> 4)]) + utf8.append(hexDigits[Int(byte & 0x0F)]) + } + return String(decoding: utf8, as: UTF8.self) } } diff --git a/OpenTDFKit/NanoTDF.swift b/OpenTDFKit/NanoTDF.swift index 68de4b9..5f92e2b 100644 --- a/OpenTDFKit/NanoTDF.swift +++ b/OpenTDFKit/NanoTDF.swift @@ -59,11 +59,14 @@ public struct NanoTDF: Sendable { /// Serializes the entire NanoTDF object (header, payload, and optional signature) into a single `Data` object. /// - Returns: A `Data` object representing the serialized NanoTDF. public func toData() -> Data { - var data = Data() - data.append(header.toData()) - data.append(payload.toData()) - if let signature { - data.append(signature.toData()) + let headerData = header.toData() + let payloadData = payload.toData() + let signatureData = signature?.toData() + var data = Data(capacity: headerData.count + payloadData.count + (signatureData?.count ?? 0)) + data.append(headerData) + data.append(payloadData) + if let signatureData { + data.append(signatureData) } return data } @@ -582,7 +585,7 @@ public struct Payload: Sendable { /// - Returns: A `Data` object representing the serialized payload. public func toData() -> Data { let clampedLength = min(length, 0xFFFFFF) - var data = Data() + var data = Data(capacity: 3 + iv.count + ciphertext.count + mac.count) // Serialize length as UInt24 (3 bytes) data.append(UInt8((clampedLength >> 16) & 0xFF)) data.append(UInt8((clampedLength >> 8) & 0xFF)) diff --git a/OpenTDFKit/NanoTDFCollection.swift b/OpenTDFKit/NanoTDFCollection.swift index 7f4d591..38470bf 100644 --- a/OpenTDFKit/NanoTDFCollection.swift +++ b/OpenTDFKit/NanoTDFCollection.swift @@ -319,10 +319,10 @@ public actor NanoTDFCollection { nonceBuffer[1] = UInt8((iv >> 8) & 0xFF) nonceBuffer[2] = UInt8(iv & 0xFF) - // Use CryptoKit for 128-bit tags (fastest path) + // Use CryptoKit for 128-bit tags (fastest path, zero heap allocation for nonce) if configuration.cipher == .aes256GCM128 { - let nonce = try nonceBuffer.withUnsafeBufferPointer { buffer in - try AES.GCM.Nonce(data: Data(buffer)) + let nonce = try nonceBuffer.withUnsafeBytes { buffer in + try AES.GCM.Nonce(data: buffer) } let sealed = try AES.GCM.seal(plaintext, using: symmetricKey, nonce: nonce) return CollectionItem(ivCounter: iv, ciphertext: sealed.ciphertext, tag: sealed.tag) @@ -376,13 +376,17 @@ public actor NanoTDFCollection { /// - Throws: `NanoTDFCollectionError.frameTooLarge` if the length field cannot represent the item. public func serialize(item: CollectionItem, format: CollectionWireFormat? = nil) throws -> Data { let wireFormat = format ?? configuration.wireFormat - var data = Data() + let contentLength = item.ciphertextWithTag.count + let headerSize = wireFormat == .containerFraming ? 6 : 7 + var data = Data(capacity: headerSize + contentLength) - // Write IV (3 bytes) - data.append(contentsOf: item.iv) + // Write IV (3 bytes) directly from counter without intermediate Data allocation + let iv = item.ivCounter + data.append(UInt8((iv >> 16) & 0xFF)) + data.append(UInt8((iv >> 8) & 0xFF)) + data.append(UInt8(iv & 0xFF)) // Write length - let contentLength = item.ciphertextWithTag.count switch wireFormat { case .containerFraming: guard contentLength <= 0xFFFFFF else { diff --git a/OpenTDFKit/NanoTDFCollectionDecryptor.swift b/OpenTDFKit/NanoTDFCollectionDecryptor.swift index 331b628..32422c9 100644 --- a/OpenTDFKit/NanoTDFCollectionDecryptor.swift +++ b/OpenTDFKit/NanoTDFCollectionDecryptor.swift @@ -32,9 +32,6 @@ public actor NanoTDFCollectionDecryptor { /// The cipher used for encryption private let cipher: Cipher - /// Pre-allocated 12-byte nonce buffer (reused for each decryption) - private var nonceBuffer: ContiguousArray - // MARK: - Factory Methods /// Creates a decryptor with an already-unwrapped symmetric key without verifying @@ -149,29 +146,33 @@ public actor NanoTDFCollectionDecryptor { private init(symmetricKey: SymmetricKey, cipher: Cipher) { self.symmetricKey = symmetricKey self.cipher = cipher - nonceBuffer = ContiguousArray(repeating: 0, count: 12) } // MARK: - Decryption - /// Decrypts a single collection item + /// Decrypts a single collection item without serializing on the actor executor. /// /// - Parameter item: The CollectionItem to decrypt /// - Returns: The decrypted plaintext data /// - Throws: `NanoTDFCollectionError.decryptionFailed` if decryption fails - public func decryptItem(_ item: CollectionItem) throws -> Data { - // Update nonce buffer with item's IV (first 3 bytes) + public nonisolated func decryptItem(_ item: CollectionItem) async throws -> Data { + try decryptItemSync(item) + } + + /// Synchronous, nonisolated decryption path for callers that do not need `async`. + public nonisolated func decryptItemSync(_ item: CollectionItem) throws -> Data { let iv = item.ivCounter - nonceBuffer[0] = UInt8((iv >> 16) & 0xFF) - nonceBuffer[1] = UInt8((iv >> 8) & 0xFF) - nonceBuffer[2] = UInt8(iv & 0xFF) + let nonceTuple: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) = ( + UInt8((iv >> 16) & 0xFF), + UInt8((iv >> 8) & 0xFF), + UInt8(iv & 0xFF), + 0, 0, 0, 0, 0, 0, 0, 0, 0, + ) - // Use CryptoKit for 128-bit tags (fastest path) + // Use CryptoKit for 128-bit tags (fastest path, zero heap allocation for nonce) if cipher == .aes256GCM128 { do { - let nonce = try nonceBuffer.withUnsafeBufferPointer { buffer in - try AES.GCM.Nonce(data: Data(buffer)) - } + let nonce = try withUnsafeBytes(of: nonceTuple) { try AES.GCM.Nonce(data: $0) } let sealedBox = try AES.GCM.SealedBox( nonce: nonce, ciphertext: item.ciphertext, @@ -185,10 +186,11 @@ public actor NanoTDFCollectionDecryptor { // For truncated tag sizes, use CryptoHelper's constant-time CommonCrypto CTR + CryptoKit GCM path do { + let ivData = withUnsafeBytes(of: nonceTuple) { Data($0) } return try CryptoHelper.decryptNanoTDF( cipher: cipher, key: symmetricKey, - iv: Data(nonceBuffer), + iv: ivData, ciphertext: item.ciphertext, tag: item.tag, ) @@ -197,17 +199,17 @@ public actor NanoTDFCollectionDecryptor { } } - /// Decrypts multiple collection items efficiently + /// Decrypts multiple collection items efficiently without serializing on the actor executor. /// /// - Parameter items: Array of CollectionItems to decrypt /// - Returns: Array of decrypted plaintext data in the same order as input /// - Throws: `NanoTDFCollectionError.decryptionFailed` if any decryption fails - public func decryptBatch(_ items: [CollectionItem]) throws -> [Data] { + public nonisolated func decryptBatch(_ items: [CollectionItem]) async throws -> [Data] { var results = [Data]() results.reserveCapacity(items.count) for item in items { - try results.append(decryptItem(item)) + try results.append(decryptItemSync(item)) } return results @@ -217,7 +219,7 @@ public actor NanoTDFCollectionDecryptor { /// /// - Parameter item: The CollectionItem to decrypt /// - Returns: The decrypted plaintext data, or nil if decryption fails - public func tryDecryptItem(_ item: CollectionItem) -> Data? { - try? decryptItem(item) + public nonisolated func tryDecryptItem(_ item: CollectionItem) async -> Data? { + try? decryptItemSync(item) } } diff --git a/OpenTDFKit/PublicKeyStore.swift b/OpenTDFKit/PublicKeyStore.swift index da03327..c7e751c 100644 --- a/OpenTDFKit/PublicKeyStore.swift +++ b/OpenTDFKit/PublicKeyStore.swift @@ -5,7 +5,8 @@ import Foundation public final class PublicKeyStore: Sendable { public let curve: Curve private actor InternalStore { - var keys: [Data] = [] + private var keys: [Data] = [] + private var head: Int = 0 func addKey(_ key: Data) { keys.append(key) @@ -16,22 +17,34 @@ public final class PublicKeyStore: Sendable { } func getAndRemoveKey() throws -> Data { - guard !keys.isEmpty else { + guard head < keys.count else { throw PublicKeyStoreError.noKeysAvailable } - return keys.removeFirst() + let key = keys[head] + head += 1 + // Amortized O(1) FIFO pop: compact only when at least half the buffer is consumed. + if head >= keys.count { + keys.removeAll(keepingCapacity: true) + head = 0 + } else if head >= 64, head * 2 >= keys.count { + keys.removeFirst(head) + head = 0 + } + return key } func getKeys() -> [Data] { - keys + head == 0 ? keys : Array(keys[head...]) } func clear() { keys.removeAll() + head = 0 } func replaceAll(_ newKeys: [Data]) { keys = newKeys + head = 0 } } diff --git a/OpenTDFKit/TDF/StreamingTDFCrypto.swift b/OpenTDFKit/TDF/StreamingTDFCrypto.swift index cb7e203..932bd66 100644 --- a/OpenTDFKit/TDF/StreamingTDFCrypto.swift +++ b/OpenTDFKit/TDF/StreamingTDFCrypto.swift @@ -441,8 +441,8 @@ public enum StreamingTDFCrypto { } private static func computeSegmentSignature( - ivData: Data, - ciphertext: Data, + ivData: some DataProtocol, + ciphertext: some DataProtocol, tagData: Data, algorithm: String, symmetricKey: SymmetricKey, @@ -461,6 +461,135 @@ public enum StreamingTDFCrypto { } } + /// Single-pass streaming multi-segment decryption directly to `outputURL`. + /// Decrypts and verifies each segment's GCM tag and manifest hash into a private (`0600`) + /// staging file beside `outputURL`, then verifies the HS256 root signature before atomically + /// moving the staging file into place. Removes the staging file on any failure, cutting disk + /// I/O and AES-GCM CPU in half compared to two-pass `FileHandle` decryption. + public static func decryptPayloadStreamingMultiSegment( + inputHandle: FileHandle, + outputURL: URL, + segments: [EncryptedSegment], + symmetricKey: SymmetricKey, + chunkSize: Int = defaultChunkSize, + rootSignature: String, + segmentHashAlg: String = "GMAC", + ) throws { + guard chunkSize > 0 else { throw StreamingCryptoError.invalidChunkSize } + guard !segments.isEmpty else { throw StreamingCryptoError.malformedSegment(0) } + + let startOffset = try inputHandle.offset() + let endOffset = try inputHandle.seekToEnd() + guard endOffset >= startOffset else { throw StreamingCryptoError.segmentReadFailed } + try inputHandle.seek(toOffset: startOffset) + + let stagingURL = outputURL.deletingLastPathComponent() + .appendingPathComponent(".\(outputURL.lastPathComponent).\(UUID().uuidString).partial") + let fd = open(stagingURL.path, O_CREAT | O_EXCL | O_WRONLY, 0o600) + guard fd >= 0 else { + throw StreamingCryptoError.segmentReadFailed + } + let stagingHandle = FileHandle(fileDescriptor: fd, closeOnDealloc: false) + var stagingClosed = false + var committed = false + defer { + if !stagingClosed { + try? stagingHandle.close() + } + if !committed { + try? FileManager.default.removeItem(at: stagingURL) + } + } + + var currentOffset = startOffset + var segmentSignatures: [Data] = [] + segmentSignatures.reserveCapacity(segments.count) + + for segment in segments { + try autoreleasepool { + guard segment.encryptedSize >= 28, + let segmentSizeInt = Int(exactly: segment.encryptedSize) + else { + throw StreamingCryptoError.malformedSegment(segment.segmentIndex) + } + let segmentSize = UInt64(segment.encryptedSize) + guard currentOffset <= endOffset, segmentSize <= endOffset - currentOffset else { + throw StreamingCryptoError.malformedSegment(segment.segmentIndex) + } + + let ivData = try inputHandle.read(upToCount: 12) ?? Data() + guard ivData.count == 12 else { + throw StreamingCryptoError.malformedSegment(segment.segmentIndex) + } + + let ciphertextSize = segmentSizeInt - 28 + var ciphertextAccumulator = Data() + ciphertextAccumulator.reserveCapacity(ciphertextSize) + var totalRead = 0 + while totalRead < ciphertextSize { + let remaining = ciphertextSize - totalRead + let readSize = min(remaining, chunkSize) + guard let chunk = try inputHandle.read(upToCount: readSize), !chunk.isEmpty else { + throw StreamingCryptoError.segmentReadFailed + } + ciphertextAccumulator.append(chunk) + totalRead += chunk.count + } + + let tagData = try inputHandle.read(upToCount: 16) ?? Data() + guard tagData.count == 16 else { + throw StreamingCryptoError.malformedSegment(segment.segmentIndex) + } + + let computedSig = try computeSegmentSignature( + ivData: ivData, + ciphertext: ciphertextAccumulator, + tagData: tagData, + algorithm: segmentHashAlg, + symmetricKey: symmetricKey, + ) + guard let expectedHash = Data(base64Encoded: segment.hash), + CryptoHelper.constantTimeEquals(expectedHash, computedSig) + else { + throw StreamingCryptoError.integrityCheckFailed + } + + let nonce = try AES.GCM.Nonce(data: ivData) + let sealed = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertextAccumulator, tag: tagData) + var plaintext = try AES.GCM.open(sealed, using: symmetricKey) + defer { plaintext.secureZero() } + try stagingHandle.write(contentsOf: plaintext) + + segmentSignatures.append(computedSig) + currentOffset += segmentSize + } + } + + guard currentOffset == endOffset else { + throw StreamingCryptoError.malformedSegment(segments.last?.segmentIndex ?? 0) + } + + let computedRoot = Data(HMAC.authenticationCode( + for: Data(segmentSignatures.joined()), + using: symmetricKey, + )) + guard let expectedRoot = Data(base64Encoded: rootSignature), + CryptoHelper.constantTimeEquals(expectedRoot, computedRoot) + else { + throw StreamingCryptoError.integrityCheckFailed + } + + try stagingHandle.close() + stagingClosed = true + + if FileManager.default.fileExists(atPath: outputURL.path) { + _ = try FileManager.default.replaceItemAt(outputURL, withItemAt: stagingURL) + } else { + try FileManager.default.moveItem(at: stagingURL, to: outputURL) + } + committed = true + } + public static func decryptPayloadStreamingMultiSegment( inputHandle: FileHandle, outputHandle: FileHandle, @@ -645,14 +774,15 @@ public enum StreamingTDFCrypto { } let start = encryptedPayload.startIndex + offset - let ivData = Data(encryptedPayload[start ..< start + 12]) + let ivSlice = encryptedPayload[start ..< start + 12] let ciphertextSize = segmentSize - 28 - let ciphertextData = Data(encryptedPayload[start + 12 ..< start + 12 + ciphertextSize]) - let tagData = Data(encryptedPayload[start + 12 + ciphertextSize ..< start + segmentSize]) + let ciphertextSlice = encryptedPayload[start + 12 ..< start + 12 + ciphertextSize] + let tagSlice = encryptedPayload[start + 12 + ciphertextSize ..< start + segmentSize] + let tagData = Data(tagSlice) let computedSig = try computeSegmentSignature( - ivData: ivData, - ciphertext: ciphertextData, + ivData: ivSlice, + ciphertext: ciphertextSlice, tagData: tagData, algorithm: segmentHashAlg, symmetricKey: symmetricKey, @@ -663,8 +793,8 @@ public enum StreamingTDFCrypto { throw StreamingCryptoError.integrityCheckFailed } - let nonce = try AES.GCM.Nonce(data: ivData) - let sealed = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertextData, tag: tagData) + let nonce = try AES.GCM.Nonce(data: ivSlice) + let sealed = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertextSlice, tag: tagSlice) let segmentPlaintext = try AES.GCM.open(sealed, using: symmetricKey) plaintext.append(segmentPlaintext) diff --git a/OpenTDFKit/TDF/StrictJSON.swift b/OpenTDFKit/TDF/StrictJSON.swift index 3eb5ded..6c57b64 100644 --- a/OpenTDFKit/TDF/StrictJSON.swift +++ b/OpenTDFKit/TDF/StrictJSON.swift @@ -13,20 +13,23 @@ enum StrictJSON { /// `true` when any object in `data` repeats a member name, or when the /// input can't be scanned. static func hasDuplicateMembers(_ data: Data) -> Bool { - var scanner = Scanner(bytes: Array(data)) - guard let duplicate = try? scanner.scanValue(depth: 0) else { - return true + data.withUnsafeBytes { rawBuffer in + let bytes = rawBuffer.bindMemory(to: UInt8.self) + var scanner = Scanner(bytes: bytes) + guard let duplicate = try? scanner.scanValue(depth: 0) else { + return true + } + return duplicate } - return duplicate } private struct ScanError: Error {} private struct Scanner { - let bytes: [UInt8] + let bytes: UnsafeBufferPointer var index = 0 - init(bytes: [UInt8]) { + init(bytes: UnsafeBufferPointer) { self.bytes = bytes } @@ -159,7 +162,7 @@ enum StrictJSON { guard let unicode = Unicode.Scalar(scalar) else { throw ScanError() } - utf8.append(contentsOf: Array(String(Character(unicode)).utf8)) + utf8.append(contentsOf: unicode.utf8) default: throw ScanError() } @@ -171,18 +174,33 @@ enum StrictJSON { } mutating func scanHex4() throws -> UInt32 { - guard index + 4 <= bytes.count, - let value = UInt32(String(decoding: bytes[index ..< index + 4], as: UTF8.self), radix: 16) - else { + guard index + 4 <= bytes.count else { throw ScanError() } + var value: UInt32 = 0 + for offset in 0 ..< 4 { + let b = bytes[index + offset] + let digit: UInt32 + switch b { + case 0x30 ... 0x39: digit = UInt32(b - 0x30) + case 0x41 ... 0x46: digit = UInt32(b - 0x41 + 10) + case 0x61 ... 0x66: digit = UInt32(b - 0x61 + 10) + default: throw ScanError() + } + value = (value << 4) | digit + } index += 4 return value } mutating func skipWhitespace() { - while index < bytes.count, [0x20, 0x09, 0x0A, 0x0D].contains(bytes[index]) { - index += 1 + while index < bytes.count { + switch bytes[index] { + case 0x20, 0x09, 0x0A, 0x0D: + index += 1 + default: + return + } } } @@ -191,7 +209,12 @@ enum StrictJSON { } static func isDelimiter(_ byte: UInt8) -> Bool { - [UInt8(ascii: ","), UInt8(ascii: "}"), UInt8(ascii: "]"), 0x20, 0x09, 0x0A, 0x0D].contains(byte) + switch byte { + case UInt8(ascii: ","), UInt8(ascii: "}"), UInt8(ascii: "]"), 0x20, 0x09, 0x0A, 0x0D: + true + default: + false + } } } } diff --git a/OpenTDFKit/TDF/TDFCBORContainer.swift b/OpenTDFKit/TDF/TDFCBORContainer.swift index 414fb82..4dd72d0 100644 --- a/OpenTDFKit/TDF/TDFCBORContainer.swift +++ b/OpenTDFKit/TDF/TDFCBORContainer.swift @@ -122,7 +122,10 @@ public struct TDFCBORBuilder: Sendable { ) // Combine IV + ciphertext + tag for the payload (as raw bytes) - let payloadData = iv + ciphertext + tag + var payloadData = Data(capacity: iv.count + ciphertext.count + tag.count) + payloadData.append(iv) + payloadData.append(ciphertext) + payloadData.append(tag) // Wrap the symmetric key using EC (ECDH + HKDF + AES-GCM) let ecWrapped = try TDFCrypto.wrapSymmetricKeyWithEC( @@ -297,46 +300,12 @@ public struct TDFCBORDecryptor: Sendable { /// Decrypt a TDF-CBOR container with an EC private key (unwraps the symmetric key first). /// Explicitly rejects split-key containers and non-EC-wrapped key access objects. public func decrypt(container: TDFCBORContainer, privateKeyPEM: String) throws -> Data { - let keyAccess = container.encryptionInformation.keyAccess - guard !keyAccess.isEmpty else { - throw TDFCBORError.decryptionFailed("No key access objects found") - } - - let distinctSplits = Set(keyAccess.map { $0.sid ?? "" }) - guard distinctSplits.count == 1 else { - throw TDFCBORError.decryptionFailed("Split-key TDF-CBOR containers with multiple split IDs are not supported by single-key decrypt") - } - - let ecObjects = keyAccess.filter { $0.type == .ecWrapped } - guard !ecObjects.isEmpty else { - throw TDFCBORError.decryptionFailed("No ec-wrapped key access object found") - } - - var lastError: Error? - for kao in ecObjects { - guard let ephemeralPublicKey = kao.ephemeralPublicKey else { - lastError = TDFCBORError.decryptionFailed("EC-wrapped key missing ephemeral public key") - continue - } - do { - let symmetricKey = try TDFCrypto.unwrapSymmetricKeyWithEC( - privateKeyPEM: privateKeyPEM, - wrappedKey: kao.wrappedKey, - ephemeralPublicKey: ephemeralPublicKey, - ) - guard TDFCrypto.verifyPolicyBinding( - kao.policyBinding, - policyBase64: container.encryptionInformation.policy, - symmetricKey: symmetricKey, - ) else { - lastError = TDFDecryptError.policyBindingFailed - continue - } - return try decrypt(container: container, symmetricKey: symmetricKey) - } catch { - lastError = error - } - } - throw lastError ?? TDFCBORError.decryptionFailed("Failed to unwrap EC key access object") + let symmetricKey = try TDFDecryptor.unwrapSingleSplitECKey( + encryptionInfo: container.encryptionInformation, + privateKeyPEM: privateKeyPEM, + formatLabel: "TDF-CBOR", + makeError: { TDFCBORError.decryptionFailed($0) }, + ) + return try decrypt(container: container, symmetricKey: symmetricKey) } } diff --git a/OpenTDFKit/TDF/TDFCrypto.swift b/OpenTDFKit/TDF/TDFCrypto.swift index c963b6c..081dac7 100644 --- a/OpenTDFKit/TDF/TDFCrypto.swift +++ b/OpenTDFKit/TDF/TDFCrypto.swift @@ -1,5 +1,5 @@ +import CommonCrypto import CryptoKit -import CryptoSwift import Foundation import Security @@ -120,59 +120,126 @@ public enum TDFCrypto { // MARK: - AES-CBC Encryption (FairPlay Compatible) - /// Encrypt payload using AES-CBC with PKCS7 padding. + /// Encrypt payload using AES-CBC with PKCS7 padding via hardware-accelerated CommonCrypto. /// This mode is compatible with FairPlay Streaming. /// - Parameters: /// - plaintext: Data to encrypt /// - symmetricKey: Symmetric key (16 or 32 bytes) /// - Returns: Tuple of (iv, ciphertext) public static func encryptPayloadCBC(plaintext: Data, symmetricKey: SymmetricKey) throws -> (iv: Data, cipherText: Data) { - let ivData = try randomBytes(count: 16) // CBC uses 16-byte IV - var keyBytes = symmetricKey.withUnsafeBytes { Array($0) } - defer { - keyBytes.withUnsafeMutableBytes { buffer in - guard let baseAddress = buffer.baseAddress else { return } - memset_s(baseAddress, buffer.count, 0, buffer.count) - } + let bitCount = symmetricKey.bitCount + guard bitCount == 128 || bitCount == 192 || bitCount == 256 else { + throw TDFCryptoError.cbcEncryptionFailed("Unsupported AES key size: \(bitCount) bits") } - let aes = try CryptoSwift.AES( - key: keyBytes, - blockMode: CryptoSwift.CBC(iv: Array(ivData)), - padding: .pkcs7, + let ivData = try randomBytes(count: kCCBlockSizeAES128) // CBC uses 16-byte IV + let ciphertext = try aesCBCTransform( + operation: CCOperation(kCCEncrypt), + input: plaintext, + iv: ivData, + symmetricKey: symmetricKey, ) - - let ciphertext = try aes.encrypt(Array(plaintext)) - return (ivData, Data(ciphertext)) + return (ivData, ciphertext) } - /// Decrypt payload using AES-CBC with PKCS7 padding. + /// Decrypt payload using AES-CBC with PKCS7 padding via hardware-accelerated CommonCrypto. /// - Parameters: /// - ciphertext: Encrypted data /// - iv: Initialization vector (16 bytes) - /// - symmetricKey: Symmetric key + /// - symmetricKey: Symmetric key (16 or 32 bytes) /// - Returns: Decrypted plaintext public static func decryptPayloadCBC(ciphertext: Data, iv: Data, symmetricKey: SymmetricKey) throws -> Data { - guard iv.count == 16 else { - throw TDFCryptoError.invalidIVSize(expected: 16, actual: iv.count) + guard iv.count == kCCBlockSizeAES128 else { + throw TDFCryptoError.invalidIVSize(expected: kCCBlockSizeAES128, actual: iv.count) + } + let bitCount = symmetricKey.bitCount + guard bitCount == 128 || bitCount == 192 || bitCount == 256 else { + throw TDFCryptoError.cbcDecryptionFailed("Unsupported AES key size: \(bitCount) bits") + } + guard !ciphertext.isEmpty, ciphertext.count % kCCBlockSizeAES128 == 0 else { + throw TDFCryptoError.cbcDecryptionFailed("Ciphertext length must be a non-zero multiple of 16 bytes") } - var keyBytes = symmetricKey.withUnsafeBytes { Array($0) } - defer { - keyBytes.withUnsafeMutableBytes { buffer in - guard let baseAddress = buffer.baseAddress else { return } - memset_s(baseAddress, buffer.count, 0, buffer.count) + return try aesCBCTransform( + operation: CCOperation(kCCDecrypt), + input: ciphertext, + iv: iv, + symmetricKey: symmetricKey, + ) + } + + private static func aesCBCTransform( + operation: CCOperation, + input: Data, + iv: Data, + symmetricKey: SymmetricKey, + ) throws -> Data { + let isEncrypt = operation == CCOperation(kCCEncrypt) + // Use CommonCrypto PKCS7 padding on encrypt; on decrypt use raw CBC + constant-time + // PKCS7 validation so malformed padding is deterministically rejected across all OS versions. + let options: CCOptions = isEncrypt ? CCOptions(kCCOptionPKCS7Padding) : 0 + let outputCapacity = isEncrypt ? (input.count + kCCBlockSizeAES128) : input.count + var output = Data(count: outputCapacity) + var bytesMoved = 0 + + let status: CCCryptorStatus = symmetricKey.withUnsafeBytes { keyBytes in + iv.withUnsafeBytes { ivBytes in + input.withUnsafeBytes { inBytes in + output.withUnsafeMutableBytes { outBytes in + CCCrypt( + operation, + CCAlgorithm(kCCAlgorithmAES), + options, + keyBytes.baseAddress, + keyBytes.count, + ivBytes.baseAddress, + inBytes.baseAddress, + input.count, + outBytes.baseAddress, + outputCapacity, + &bytesMoved, + ) + } + } } } - let aes = try CryptoSwift.AES( - key: keyBytes, - blockMode: CryptoSwift.CBC(iv: Array(iv)), - padding: .pkcs7, - ) + guard status == kCCSuccess else { + output.secureZero() + if isEncrypt { + throw TDFCryptoError.cbcEncryptionFailed("CommonCrypto status \(status)") + } else { + throw TDFCryptoError.cbcDecryptionFailed("CommonCrypto status \(status)") + } + } + + if isEncrypt { + output.removeSubrange(bytesMoved ..< output.count) + return output + } + + guard bytesMoved == input.count, bytesMoved >= kCCBlockSizeAES128 else { + output.secureZero() + throw TDFCryptoError.cbcDecryptionFailed("Unexpected decrypted byte count") + } + + // Constant-time PKCS7 padding verification over the final 16-byte block. + let padByte = output[bytesMoved - 1] + let padLen = Int(padByte) + var bad: UInt8 = (padLen >= 1 && padLen <= kCCBlockSizeAES128) ? 0 : 1 + let clampedPadLen = min(max(padLen, 0), kCCBlockSizeAES128) + for offset in 0 ..< kCCBlockSizeAES128 { + let mask = UInt8(truncatingIfNeeded: (offset &- clampedPadLen) >> (Int.bitWidth - 1)) + let diff = output[bytesMoved - 1 - offset] ^ padByte + bad |= diff & mask + } + guard bad == 0 else { + output.secureZero() + throw TDFCryptoError.cbcDecryptionFailed("Invalid PKCS7 padding") + } - let plaintext = try aes.decrypt(Array(ciphertext)) - return Data(plaintext) + output.removeSubrange((bytesMoved - padLen) ..< bytesMoved) + return output } /// Compute the Standard TDF policy binding: `Base64(HMAC-SHA256(DEK, Base64(policyJSON)))`, @@ -312,16 +379,10 @@ public enum TDFCrypto { } public static func loadRSAPublicKey(fromPEM pem: String) throws -> SecKey { - let stripped = pem - .replacingOccurrences(of: "-----BEGIN PUBLIC KEY-----", with: "") - .replacingOccurrences(of: "-----END PUBLIC KEY-----", with: "") - .replacingOccurrences(of: "\n", with: "") - .replacingOccurrences(of: "\r", with: "") - .trimmingCharacters(in: .whitespacesAndNewlines) - - guard let data = Data(base64Encoded: stripped) else { - throw TDFCryptoError.invalidPEM - } + let data = try decodePEMBody(pem, markers: [ + "-----BEGIN PUBLIC KEY-----", + "-----END PUBLIC KEY-----", + ]) let attributes: [String: Any] = [ kSecAttrKeyType as String: kSecAttrKeyTypeRSA, @@ -338,18 +399,12 @@ public enum TDFCrypto { } public static func loadRSAPrivateKey(fromPEM pem: String) throws -> SecKey { - let stripped = pem - .replacingOccurrences(of: "-----BEGIN RSA PRIVATE KEY-----", with: "") - .replacingOccurrences(of: "-----END RSA PRIVATE KEY-----", with: "") - .replacingOccurrences(of: "-----BEGIN PRIVATE KEY-----", with: "") - .replacingOccurrences(of: "-----END PRIVATE KEY-----", with: "") - .replacingOccurrences(of: "\n", with: "") - .replacingOccurrences(of: "\r", with: "") - .trimmingCharacters(in: .whitespacesAndNewlines) - - guard let data = Data(base64Encoded: stripped) else { - throw TDFCryptoError.invalidPEM - } + let data = try decodePEMBody(pem, markers: [ + "-----BEGIN RSA PRIVATE KEY-----", + "-----END RSA PRIVATE KEY-----", + "-----BEGIN PRIVATE KEY-----", + "-----END PRIVATE KEY-----", + ]) let attributes: [String: Any] = [ kSecAttrKeyType as String: kSecAttrKeyTypeRSA, @@ -365,6 +420,22 @@ public enum TDFCrypto { return key } + private static func decodePEMBody(_ pem: String, markers: [String]) throws -> Data { + var stripped = pem + for marker in markers { + stripped = stripped.replacingOccurrences(of: marker, with: "") + } + stripped = stripped + .replacingOccurrences(of: "\n", with: "") + .replacingOccurrences(of: "\r", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines) + + guard let data = Data(base64Encoded: stripped) else { + throw TDFCryptoError.invalidPEM + } + return data + } + private static func validateRSAKeySize(_ key: SecKey, minimumBits: Int) throws { guard let attributes = SecKeyCopyAttributes(key) as? [String: Any], let keySize = attributes[kSecAttrKeySizeInBits as String] as? Int @@ -545,8 +616,11 @@ public enum TDFCrypto { let wrapKey = try deriveKASWrapKey(ephemeralPrivateKey, kasPublicKey) // Seal straight from the key's own storage, so no copy of the share is left behind. let sealed = try symmetricKey.withUnsafeBytes { try AES.GCM.seal($0, using: wrapKey) } + guard let combined = sealed.combined else { + throw TDFCryptoError.keyWrapFailed(nil) + } return KASECWrappedKey( - wrappedKey: sealed.combined!.base64EncodedString(), + wrappedKey: combined.base64EncodedString(), ephemeralPublicKeyPEM: ephemeralPrivateKey.publicKey.pemRepresentation, ) } @@ -566,110 +640,75 @@ public enum TDFCrypto { ) } - // MARK: - P-256 EC Wrapping - - private static func wrapWithP256(publicKeyPEM: String, symmetricKey: SymmetricKey) throws -> ECWrappedKeyResult { - // Load recipient's public key - let recipientPublicKey = try loadECPublicKeyP256(fromPEM: publicKeyPEM) - - // Generate ephemeral key pair - let ephemeralPrivateKey = P256.KeyAgreement.PrivateKey() - let ephemeralPublicKey = ephemeralPrivateKey.publicKey + // MARK: - EC Wrapping Helpers (TDF-JSON / TDF-CBOR draft scheme) - // Perform ECDH to get shared secret - let sharedSecret = try ephemeralPrivateKey.sharedSecretFromKeyAgreement(with: recipientPublicKey) - - // Derive wrapping key using HKDF-SHA256 (empty salt and info for TDF compatibility) + private static func sealECWrappedKey( + sharedSecret: SharedSecret, + ephemeralCompressedPublicKey: Data, + symmetricKey: SymmetricKey, + ) throws -> ECWrappedKeyResult { + // Derive wrapping key using HKDF-SHA256 (empty salt and info for TDF-JSON / TDF-CBOR compatibility) let wrapKey = sharedSecret.hkdfDerivedSymmetricKey( using: SHA256.self, salt: Data(), sharedInfo: Data(), outputByteCount: 32, ) - // Seal directly from symmetricKey storage so no unzeroed copy is left behind let nonce = try AES.GCM.Nonce(data: randomBytes(count: 12)) let sealed = try symmetricKey.withUnsafeBytes { try AES.GCM.seal($0, using: wrapKey, nonce: nonce) } - - // Combined format: nonce + ciphertext + tag - let wrappedKey = sealed.combined!.base64EncodedString() - - // Convert ephemeral public key to compressed SEC1 format (33 bytes for P-256) - // Much smaller than PEM (~140 bytes) or uncompressed (65 bytes) - let ephemeralCompressed = ephemeralPublicKey.compressedRepresentation.base64EncodedString() - - return ECWrappedKeyResult(wrappedKey: wrappedKey, ephemeralPublicKey: ephemeralCompressed) + guard let combined = sealed.combined else { + throw TDFCryptoError.keyWrapFailed(nil) + } + return ECWrappedKeyResult( + wrappedKey: combined.base64EncodedString(), + ephemeralPublicKey: ephemeralCompressedPublicKey.base64EncodedString(), + ) } - // MARK: - P-384 EC Wrapping + private static func wrapWithP256(publicKeyPEM: String, symmetricKey: SymmetricKey) throws -> ECWrappedKeyResult { + let recipientPublicKey = try loadECPublicKeyP256(fromPEM: publicKeyPEM) + let ephemeralPrivateKey = P256.KeyAgreement.PrivateKey() + let sharedSecret = try ephemeralPrivateKey.sharedSecretFromKeyAgreement(with: recipientPublicKey) + return try sealECWrappedKey( + sharedSecret: sharedSecret, + ephemeralCompressedPublicKey: ephemeralPrivateKey.publicKey.compressedRepresentation, + symmetricKey: symmetricKey, + ) + } private static func wrapWithP384(publicKeyPEM: String, symmetricKey: SymmetricKey) throws -> ECWrappedKeyResult { let recipientPublicKey = try loadECPublicKeyP384(fromPEM: publicKeyPEM) - let ephemeralPrivateKey = P384.KeyAgreement.PrivateKey() - let ephemeralPublicKey = ephemeralPrivateKey.publicKey - let sharedSecret = try ephemeralPrivateKey.sharedSecretFromKeyAgreement(with: recipientPublicKey) - - let wrapKey = sharedSecret.hkdfDerivedSymmetricKey( - using: SHA256.self, - salt: Data(), - sharedInfo: Data(), - outputByteCount: 32, + return try sealECWrappedKey( + sharedSecret: sharedSecret, + ephemeralCompressedPublicKey: ephemeralPrivateKey.publicKey.compressedRepresentation, + symmetricKey: symmetricKey, ) - - let nonce = try AES.GCM.Nonce(data: randomBytes(count: 12)) - let sealed = try symmetricKey.withUnsafeBytes { try AES.GCM.seal($0, using: wrapKey, nonce: nonce) } - - let wrappedKey = sealed.combined!.base64EncodedString() - // Compressed SEC1 format (49 bytes for P-384) - let ephemeralCompressed = ephemeralPublicKey.compressedRepresentation.base64EncodedString() - - return ECWrappedKeyResult(wrappedKey: wrappedKey, ephemeralPublicKey: ephemeralCompressed) } - // MARK: - P-521 EC Wrapping - private static func wrapWithP521(publicKeyPEM: String, symmetricKey: SymmetricKey) throws -> ECWrappedKeyResult { let recipientPublicKey = try loadECPublicKeyP521(fromPEM: publicKeyPEM) - let ephemeralPrivateKey = P521.KeyAgreement.PrivateKey() - let ephemeralPublicKey = ephemeralPrivateKey.publicKey - let sharedSecret = try ephemeralPrivateKey.sharedSecretFromKeyAgreement(with: recipientPublicKey) - - let wrapKey = sharedSecret.hkdfDerivedSymmetricKey( - using: SHA256.self, - salt: Data(), - sharedInfo: Data(), - outputByteCount: 32, + return try sealECWrappedKey( + sharedSecret: sharedSecret, + ephemeralCompressedPublicKey: ephemeralPrivateKey.publicKey.compressedRepresentation, + symmetricKey: symmetricKey, ) - - let nonce = try AES.GCM.Nonce(data: randomBytes(count: 12)) - let sealed = try symmetricKey.withUnsafeBytes { try AES.GCM.seal($0, using: wrapKey, nonce: nonce) } - - let wrappedKey = sealed.combined!.base64EncodedString() - // Compressed SEC1 format (67 bytes for P-521) - let ephemeralCompressed = ephemeralPublicKey.compressedRepresentation.base64EncodedString() - - return ECWrappedKeyResult(wrappedKey: wrappedKey, ephemeralPublicKey: ephemeralCompressed) } // MARK: - EC Public Key Loading + private static let publicKeyPEMMarkers = [ + "-----BEGIN PUBLIC KEY-----", + "-----END PUBLIC KEY-----", + ] + /// Load a P-256 EC public key from PEM format public static func loadECPublicKeyP256(fromPEM pem: String) throws -> P256.KeyAgreement.PublicKey { - let stripped = pem - .replacingOccurrences(of: "-----BEGIN PUBLIC KEY-----", with: "") - .replacingOccurrences(of: "-----END PUBLIC KEY-----", with: "") - .replacingOccurrences(of: "\n", with: "") - .replacingOccurrences(of: "\r", with: "") - .trimmingCharacters(in: .whitespacesAndNewlines) - - guard let data = Data(base64Encoded: stripped) else { - throw TDFCryptoError.invalidPEM - } - + let data = try decodePEMBody(pem, markers: publicKeyPEMMarkers) do { return try P256.KeyAgreement.PublicKey(derRepresentation: data) } catch { @@ -679,17 +718,7 @@ public enum TDFCrypto { /// Load a P-384 EC public key from PEM format public static func loadECPublicKeyP384(fromPEM pem: String) throws -> P384.KeyAgreement.PublicKey { - let stripped = pem - .replacingOccurrences(of: "-----BEGIN PUBLIC KEY-----", with: "") - .replacingOccurrences(of: "-----END PUBLIC KEY-----", with: "") - .replacingOccurrences(of: "\n", with: "") - .replacingOccurrences(of: "\r", with: "") - .trimmingCharacters(in: .whitespacesAndNewlines) - - guard let data = Data(base64Encoded: stripped) else { - throw TDFCryptoError.invalidPEM - } - + let data = try decodePEMBody(pem, markers: publicKeyPEMMarkers) do { return try P384.KeyAgreement.PublicKey(derRepresentation: data) } catch { @@ -699,17 +728,7 @@ public enum TDFCrypto { /// Load a P-521 EC public key from PEM format public static func loadECPublicKeyP521(fromPEM pem: String) throws -> P521.KeyAgreement.PublicKey { - let stripped = pem - .replacingOccurrences(of: "-----BEGIN PUBLIC KEY-----", with: "") - .replacingOccurrences(of: "-----END PUBLIC KEY-----", with: "") - .replacingOccurrences(of: "\n", with: "") - .replacingOccurrences(of: "\r", with: "") - .trimmingCharacters(in: .whitespacesAndNewlines) - - guard let data = Data(base64Encoded: stripped) else { - throw TDFCryptoError.invalidPEM - } - + let data = try decodePEMBody(pem, markers: publicKeyPEMMarkers) do { return try P521.KeyAgreement.PublicKey(derRepresentation: data) } catch { diff --git a/OpenTDFKit/TDF/TDFJSONContainer.swift b/OpenTDFKit/TDF/TDFJSONContainer.swift index ea01d46..98947b0 100644 --- a/OpenTDFKit/TDF/TDFJSONContainer.swift +++ b/OpenTDFKit/TDF/TDFJSONContainer.swift @@ -121,7 +121,10 @@ public struct TDFJSONBuilder: Sendable { ) // Combine IV + ciphertext + tag for the payload - let payloadData = iv + ciphertext + tag + var payloadData = Data(capacity: iv.count + ciphertext.count + tag.count) + payloadData.append(iv) + payloadData.append(ciphertext) + payloadData.append(tag) // Wrap the symmetric key using EC (ECDH + HKDF + AES-GCM) let ecWrapped = try TDFCrypto.wrapSymmetricKeyWithEC( @@ -204,7 +207,7 @@ public struct TDFJSONBuilder: Sendable { ) // Create envelope - let created = includeCreated ? ISO8601DateFormatter().string(from: Date()) : nil + let created = includeCreated ? Date().formatted(.iso8601) : nil let envelope = TDFJSONEnvelope( tdf: "json", version: "1.0.0", @@ -309,46 +312,12 @@ public struct TDFJSONDecryptor: Sendable { /// Decrypt a TDF-JSON container with an EC private key (unwraps the symmetric key first). /// Explicitly rejects split-key manifests and non-EC-wrapped key access objects. public func decrypt(container: TDFJSONContainer, privateKeyPEM: String) throws -> Data { - let keyAccess = container.encryptionInformation.keyAccess - guard !keyAccess.isEmpty else { - throw TDFJSONError.decryptionFailed("No key access objects found") - } - - let distinctSplits = Set(keyAccess.map { $0.sid ?? "" }) - guard distinctSplits.count == 1 else { - throw TDFJSONError.decryptionFailed("Split-key TDF-JSON containers with multiple split IDs are not supported by single-key decrypt") - } - - let ecObjects = keyAccess.filter { $0.type == .ecWrapped } - guard !ecObjects.isEmpty else { - throw TDFJSONError.decryptionFailed("No ec-wrapped key access object found") - } - - var lastError: Error? - for kao in ecObjects { - guard let ephemeralPublicKey = kao.ephemeralPublicKey else { - lastError = TDFJSONError.decryptionFailed("EC-wrapped key missing ephemeral public key") - continue - } - do { - let symmetricKey = try TDFCrypto.unwrapSymmetricKeyWithEC( - privateKeyPEM: privateKeyPEM, - wrappedKey: kao.wrappedKey, - ephemeralPublicKey: ephemeralPublicKey, - ) - guard TDFCrypto.verifyPolicyBinding( - kao.policyBinding, - policyBase64: container.encryptionInformation.policy, - symmetricKey: symmetricKey, - ) else { - lastError = TDFDecryptError.policyBindingFailed - continue - } - return try decrypt(container: container, symmetricKey: symmetricKey) - } catch { - lastError = error - } - } - throw lastError ?? TDFJSONError.decryptionFailed("Failed to unwrap EC key access object") + let symmetricKey = try TDFDecryptor.unwrapSingleSplitECKey( + encryptionInfo: container.encryptionInformation, + privateKeyPEM: privateKeyPEM, + formatLabel: "TDF-JSON", + makeError: { TDFJSONError.decryptionFailed($0) }, + ) + return try decrypt(container: container, symmetricKey: symmetricKey) } } diff --git a/OpenTDFKit/TDF/TDFKAS.swift b/OpenTDFKit/TDF/TDFKAS.swift index 57cc941..54127b1 100644 --- a/OpenTDFKit/TDF/TDFKAS.swift +++ b/OpenTDFKit/TDF/TDFKAS.swift @@ -92,7 +92,10 @@ public enum TDFKAS { let sessionPrivateKey = P256.KeyAgreement.PrivateKey() let sealed = try AES.GCM.seal(share, using: TDFCrypto.deriveKASWrapKey(sessionPrivateKey, receiverPublicKey)) - return RewrapResult(wrappedKey: sealed.combined!, sessionPublicKey: sessionPrivateKey.publicKey) + guard let combined = sealed.combined else { + throw TDFKASError.keyUnwrapFailed + } + return RewrapResult(wrappedKey: combined, sessionPublicKey: sessionPrivateKey.publicKey) } /// Opens a rewrapped key share on the client, for a response that did not diff --git a/OpenTDFKit/TDF/TDFProcessor.swift b/OpenTDFKit/TDF/TDFProcessor.swift index 3bc9d03..58fa514 100644 --- a/OpenTDFKit/TDF/TDFProcessor.swift +++ b/OpenTDFKit/TDF/TDFProcessor.swift @@ -134,14 +134,6 @@ public struct TDFEncryptor { ) } - let kasObject = try makeKeyAccessObject(kas: configuration.kas, policy: configuration.policy, symmetricKey: symmetricKey) - - let method = TDFMethodDescriptor( - algorithm: configuration.keySize.algorithm, - iv: streamingResult.iv.base64EncodedString(), - isStreamable: true, - ) - let segments = streamingResult.segments.map { seg in TDFSegment( hash: seg.hash, @@ -149,59 +141,22 @@ public struct TDFEncryptor { encryptedSegmentSize: seg.encryptedSize, ) } - - // Hexless 4.3.0: root = base64(HMAC-SHA256(DEK, concat(raw GMAC tags))). let rawSegmentSigs = segments.compactMap { Data(base64Encoded: $0.hash) } - let rootSignature = TDFCrypto.rootSignatureBase64( + let result = try makeResult( + payloadData: payloadData, + segments: segments, rawSegmentSignatures: rawSegmentSigs, - symmetricKey: symmetricKey, - ) - - let integrity = TDFIntegrityInformation( - rootSignature: TDFRootSignature(alg: "HS256", sig: rootSignature), - segmentHashAlg: "GMAC", segmentSizeDefault: Int64(chunkSize), - encryptedSegmentSizeDefault: Int64(chunkSize) + 28, - segments: segments, - ) - - let encryptionInformation = TDFEncryptionInformation( - type: .split, - keyAccess: [kasObject], - method: method, - integrityInformation: integrity, - policy: configuration.policy.base64String, - ) - - let payloadDescriptor = TDFPayloadDescriptor( - type: .reference, - url: TDFArchiveEntryNames.payload, - protocolValue: .zip, - isEncrypted: true, - mimeType: configuration.mimeType, - ) - - let manifest = TDFManifest( - schemaVersion: configuration.tdfSpecVersion, - payload: payloadDescriptor, - encryptionInformation: encryptionInformation, - assertions: nil, - ) - - let container = TDFContainer( - manifest: manifest, - payload: payloadData, - ) - - try TDFArchiveWriter(compressionMethod: container.compression) - .buildArchiveToFile(manifest: container.manifest, payload: container.payload, outputURL: outputURL) - - return TDFEncryptionResult( - container: container, symmetricKey: symmetricKey, + configuration: configuration, iv: streamingResult.iv, tag: streamingResult.tag, ) + + try TDFArchiveWriter(compressionMethod: result.container.compression) + .buildArchiveToFile(manifest: result.container.manifest, payload: result.container.payload, outputURL: outputURL) + + return result } public func encryptFileMultiSegment( @@ -214,6 +169,10 @@ public struct TDFEncryptor { guard !segmentSizes.isEmpty else { throw StreamingCryptoError.invalidSegmentSize } + let defaultSegmentSize = segmentSizes.first ?? StreamingTDFCrypto.defaultChunkSize + guard defaultSegmentSize > 0, Int64(defaultSegmentSize) <= Int64.max - 28 else { + throw StreamingCryptoError.invalidSegmentSize + } let symmetricKey = try TDFCrypto.generateSymmetricKey(size: configuration.keySize) let payloadData: Data @@ -230,14 +189,6 @@ public struct TDFEncryptor { ) } - let kasObject = try makeKeyAccessObject(kas: configuration.kas, policy: configuration.policy, symmetricKey: symmetricKey) - - let method = TDFMethodDescriptor( - algorithm: configuration.keySize.algorithm, - iv: streamingResult.iv.base64EncodedString(), - isStreamable: true, - ) - let segments = streamingResult.segments.map { seg in TDFSegment( hash: seg.hash, @@ -245,58 +196,87 @@ public struct TDFEncryptor { encryptedSegmentSize: seg.encryptedSize, ) } - let rawSegmentSigs = segments.compactMap { Data(base64Encoded: $0.hash) } - let rootSignature = TDFCrypto.rootSignatureBase64( + let result = try makeResult( + payloadData: payloadData, + segments: segments, rawSegmentSignatures: rawSegmentSigs, + segmentSizeDefault: Int64(defaultSegmentSize), symmetricKey: symmetricKey, + configuration: configuration, + iv: streamingResult.iv, + tag: streamingResult.tag, ) - let defaultSegmentSize = segmentSizes.first ?? StreamingTDFCrypto.defaultChunkSize - guard defaultSegmentSize > 0, Int64(defaultSegmentSize) <= Int64.max - 28 else { + try TDFArchiveWriter(compressionMethod: result.container.compression) + .buildArchiveToFile(manifest: result.container.manifest, payload: result.container.payload, outputURL: outputURL) + + return result + } + + /// Encrypts `inputURL` directly to a TDF archive at `outputURL` using bounded O(segmentSize) + /// memory without holding the full encrypted payload in RAM. + public func encryptFileStreaming( + inputURL: URL, + outputURL: URL, + configuration: TDFEncryptionConfiguration, + segmentSize: Int = StreamingTDFCrypto.defaultChunkSize, + ) throws -> TDFStreamingFileEncryptionResult { + try validate(configuration) + guard segmentSize > 0, Int64(segmentSize) <= Int64.max - 28 else { throw StreamingCryptoError.invalidSegmentSize } - let integrity = TDFIntegrityInformation( - rootSignature: TDFRootSignature(alg: "HS256", sig: rootSignature), - segmentHashAlg: "GMAC", - segmentSizeDefault: Int64(defaultSegmentSize), - encryptedSegmentSizeDefault: Int64(defaultSegmentSize) + 28, - segments: segments, - ) - let encryptionInformation = TDFEncryptionInformation( - type: .split, - keyAccess: [kasObject], - method: method, - integrityInformation: integrity, - policy: configuration.policy.base64String, - ) + let symmetricKey = try TDFCrypto.generateSymmetricKey(size: configuration.keySize) + let tempPayloadURL = outputURL.deletingLastPathComponent() + .appendingPathComponent(".\(outputURL.lastPathComponent).\(UUID().uuidString).payload.tmp") + let fd = open(tempPayloadURL.path, O_CREAT | O_EXCL | O_WRONLY, 0o600) + guard fd >= 0 else { + throw TDFArchiveError.creationFailed + } + let tempHandle = FileHandle(fileDescriptor: fd, closeOnDealloc: false) + var tempHandleClosed = false + defer { + if !tempHandleClosed { + try? tempHandle.close() + } + try? FileManager.default.removeItem(at: tempPayloadURL) + } - let payloadDescriptor = TDFPayloadDescriptor( - type: .reference, - url: TDFArchiveEntryNames.payload, - protocolValue: .zip, - isEncrypted: true, - mimeType: configuration.mimeType, - ) + let inputHandle = try FileHandle(forReadingFrom: inputURL) + defer { try? inputHandle.close() } - let manifest = TDFManifest( - schemaVersion: configuration.tdfSpecVersion, - payload: payloadDescriptor, - encryptionInformation: encryptionInformation, - assertions: nil, + let streamingResult = try StreamingTDFCrypto.encryptPayloadStreamingMultiSegment( + inputHandle: inputHandle, + outputHandle: tempHandle, + symmetricKey: symmetricKey, + segmentSizes: [segmentSize], ) + try tempHandle.close() + tempHandleClosed = true - let container = TDFContainer( - manifest: manifest, - payload: payloadData, + let segments = streamingResult.segments.map { seg in + TDFSegment( + hash: seg.hash, + segmentSize: seg.plaintextSize, + encryptedSegmentSize: seg.encryptedSize, + ) + } + let rawSegmentSigs = segments.compactMap { Data(base64Encoded: $0.hash) } + let manifest = try makeManifest( + segments: segments, + rawSegmentSignatures: rawSegmentSigs, + segmentSizeDefault: Int64(segmentSize), + symmetricKey: symmetricKey, + configuration: configuration, + iv: streamingResult.iv, ) - try TDFArchiveWriter(compressionMethod: container.compression) - .buildArchiveToFile(manifest: container.manifest, payload: container.payload, outputURL: outputURL) + try TDFArchiveWriter(compressionMethod: .none) + .buildArchiveToFile(manifest: manifest, payloadURL: tempPayloadURL, outputURL: outputURL) - return TDFEncryptionResult( - container: container, + return TDFStreamingFileEncryptionResult( + manifest: manifest, symmetricKey: symmetricKey, iv: streamingResult.iv, tag: streamingResult.tag, @@ -308,7 +288,10 @@ public struct TDFEncryptor { let symmetricKey = try TDFCrypto.generateSymmetricKey(size: configuration.keySize) let (iv, ciphertext, tag) = try TDFCrypto.encryptPayload(plaintext: plaintext, symmetricKey: symmetricKey) - let payloadData = iv + ciphertext + tag + var payloadData = Data(capacity: iv.count + ciphertext.count + tag.count) + payloadData.append(iv) + payloadData.append(ciphertext) + payloadData.append(tag) let segmentSignature = try TDFCrypto.segmentSignatureGMAC(encryptedSegment: payloadData) let segment = TDFSegment( @@ -459,17 +442,15 @@ public struct TDFEncryptor { ) } - /// Wrap the DEK, bind the policy and assemble the manifest around an encrypted payload. - private func makeResult( - payloadData: Data, + /// Wrap the DEK, bind the policy and assemble the manifest. + private func makeManifest( segments: [TDFSegment], rawSegmentSignatures: [Data], segmentSizeDefault: Int64, symmetricKey: SymmetricKey, configuration: TDFEncryptionConfiguration, iv: Data, - tag: Data, - ) throws -> TDFEncryptionResult { + ) throws -> TDFManifest { let kasObject = try makeKeyAccessObject(kas: configuration.kas, policy: configuration.policy, symmetricKey: symmetricKey) let rootSignature = TDFCrypto.rootSignatureBase64( @@ -510,12 +491,33 @@ public struct TDFEncryptor { mimeType: configuration.mimeType, ) - let manifest = TDFManifest( + return TDFManifest( schemaVersion: configuration.tdfSpecVersion, payload: payloadDescriptor, encryptionInformation: encryptionInformation, assertions: nil, ) + } + + /// Wrap the DEK, bind the policy and assemble the manifest around an encrypted payload. + private func makeResult( + payloadData: Data, + segments: [TDFSegment], + rawSegmentSignatures: [Data], + segmentSizeDefault: Int64, + symmetricKey: SymmetricKey, + configuration: TDFEncryptionConfiguration, + iv: Data, + tag: Data, + ) throws -> TDFEncryptionResult { + let manifest = try makeManifest( + segments: segments, + rawSegmentSignatures: rawSegmentSignatures, + segmentSizeDefault: segmentSizeDefault, + symmetricKey: symmetricKey, + configuration: configuration, + iv: iv, + ) let container = TDFContainer( manifest: manifest, @@ -540,6 +542,22 @@ public struct TDFEncryptionResult: Sendable { } } +/// Result of `TDFEncryptor.encryptFileStreaming`: returns the manifest and key material +/// without holding the encrypted payload in memory. +public struct TDFStreamingFileEncryptionResult: Sendable { + public let manifest: TDFManifest + public let symmetricKey: SymmetricKey + public let iv: Data + public let tag: Data + + public init(manifest: TDFManifest, symmetricKey: SymmetricKey, iv: Data, tag: Data) { + self.manifest = manifest + self.symmetricKey = symmetricKey + self.iv = iv + self.tag = tag + } +} + public struct TDFDecryptor { public init() {} @@ -547,41 +565,147 @@ public struct TDFDecryptor { inputURL: URL, outputURL: URL, symmetricKey: SymmetricKey, - chunkSize _: Int = StreamingTDFCrypto.defaultChunkSize, + chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, ) throws { - let container = try TDFLoader().load(from: inputURL) - try decrypt(container: container, symmetricKey: symmetricKey).write(to: outputURL) + try decryptFileStreaming( + inputURL: inputURL, + outputURL: outputURL, + chunkSize: chunkSize, + resolveKey: { _ in (symmetricKey, false) }, + ) } public func decryptFile( inputURL: URL, outputURL: URL, privateKeyPEM: String, - chunkSize _: Int = StreamingTDFCrypto.defaultChunkSize, + chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, ) throws { - let loader = TDFLoader() - let container = try loader.load(from: inputURL) - - let symmetricKey = try unwrapDEK( - encryptionInformation: container.manifest.encryptionInformation, - privateKeyPEM: privateKeyPEM, + try decryptFileStreaming( + inputURL: inputURL, + outputURL: outputURL, + chunkSize: chunkSize, + resolveKey: { encryptionInfo in + let dek = try unwrapDEK(encryptionInformation: encryptionInfo, privateKeyPEM: privateKeyPEM) + return (dek, true) + }, ) - try decryptEncryptionInfo( - container.manifest.encryptionInformation, - payload: container.payload, - symmetricKey: symmetricKey, - policyBindingAlreadyVerified: true, - ).write(to: outputURL) } public func decryptFileMultiSegment( inputURL: URL, outputURL: URL, symmetricKey: SymmetricKey, - chunkSize _: Int = StreamingTDFCrypto.defaultChunkSize, + chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, ) throws { - let container = try TDFLoader().load(from: inputURL) - try decrypt(container: container, symmetricKey: symmetricKey).write(to: outputURL) + try decryptFile(inputURL: inputURL, outputURL: outputURL, symmetricKey: symmetricKey, chunkSize: chunkSize) + } + + private func decryptFileStreaming( + inputURL: URL, + outputURL: URL, + chunkSize: Int, + resolveKey: (TDFEncryptionInformation) throws -> (SymmetricKey, Bool), + ) throws { + guard chunkSize > 0 else { + throw StreamingCryptoError.invalidChunkSize + } + let reader = try TDFArchiveReader(url: inputURL) + let manifest = try reader.manifest() + let encryptionInfo = manifest.encryptionInformation + + let (symmetricKey, policyBindingAlreadyVerified) = try resolveKey(encryptionInfo) + + let expectedBits = try Self.expectedKeyBitCount(for: encryptionInfo.method.algorithm) + guard symmetricKey.bitCount == expectedBits else { + throw TDFDecryptError.keySizeMismatch(expected: expectedBits, actual: symmetricKey.bitCount) + } + guard let integrity = encryptionInfo.integrityInformation, !integrity.segments.isEmpty else { + throw TDFDecryptError.missingIntegrityInformation + } + let rootAlgorithm = integrity.rootSignature.alg + guard rootAlgorithm.isEmpty || rootAlgorithm.uppercased() == "HS256" else { + throw TDFDecryptError.unsupportedIntegrityAlgorithm(integrity.rootSignature.alg) + } + let segAlg = integrity.segmentHashAlg.uppercased() + guard segAlg == "GMAC" || segAlg == "HS256" else { + throw TDFDecryptError.unsupportedIntegrityAlgorithm(integrity.segmentHashAlg) + } + if !policyBindingAlreadyVerified { + let keyAccess = encryptionInfo.keyAccess + let distinctSplits = Set(keyAccess.map { $0.sid ?? "" }) + guard !keyAccess.isEmpty, distinctSplits.count == 1 else { + throw TDFDecryptError.policyBindingFailed + } + let bindingValid = keyAccess.contains { kao in + TDFCrypto.verifyPolicyBinding( + kao.policyBinding, + policyBase64: encryptionInfo.policy, + symmetricKey: symmetricKey, + ) + } + guard bindingValid else { + throw TDFDecryptError.policyBindingFailed + } + } + + // Stream encrypted payload out of ZIP into a private temp file, then decrypt in a single pass. + let tempEncryptedURL = outputURL.deletingLastPathComponent() + .appendingPathComponent(".\(outputURL.lastPathComponent).\(UUID().uuidString).enc.tmp") + let fd = open(tempEncryptedURL.path, O_CREAT | O_EXCL | O_RDWR, 0o600) + guard fd >= 0 else { + throw StreamingCryptoError.segmentReadFailed + } + let tempHandle = FileHandle(fileDescriptor: fd, closeOnDealloc: false) + defer { + try? tempHandle.close() + try? FileManager.default.removeItem(at: tempEncryptedURL) + } + + try reader.writePayload(to: tempHandle) + let payloadSize = try tempHandle.seekToEnd() + try tempHandle.seek(toOffset: 0) + + var streamingSegments: [StreamingTDFCrypto.EncryptedSegment] = [] + streamingSegments.reserveCapacity(integrity.segments.count) + var offset: UInt64 = 0 + for (index, segment) in integrity.segments.enumerated() { + let remaining = payloadSize - offset + let isLast = index == integrity.segments.count - 1 + guard let encryptedSize = segment.encryptedSegmentSize + ?? (isLast ? Int64(exactly: remaining) : integrity.encryptedSegmentSizeDefault), + encryptedSize >= 28, + UInt64(encryptedSize) <= remaining + else { + throw TDFDecryptError.malformedPayload + } + streamingSegments.append(StreamingTDFCrypto.EncryptedSegment( + segmentIndex: index, + plaintextSize: segment.segmentSize, + encryptedSize: encryptedSize, + hash: segment.hash, + )) + offset += UInt64(encryptedSize) + } + guard offset == payloadSize else { + throw TDFDecryptError.malformedPayload + } + + do { + try StreamingTDFCrypto.decryptPayloadStreamingMultiSegment( + inputHandle: tempHandle, + outputURL: outputURL, + segments: streamingSegments, + symmetricKey: symmetricKey, + chunkSize: chunkSize, + rootSignature: integrity.rootSignature.sig, + segmentHashAlg: integrity.segmentHashAlg, + ) + } catch StreamingCryptoError.integrityCheckFailed { + throw TDFDecryptError.integrityCheckFailed + } catch StreamingCryptoError.malformedSegment { + throw TDFDecryptError.malformedPayload + } } public func decrypt(container: TDFContainer, privateKeyPEM: String) throws -> Data { @@ -762,6 +886,57 @@ public struct TDFDecryptor { return SymmetricKey(data: dek) } + /// Unwraps a single-split EC-wrapped DEK from `encryptionInfo` and verifies its policy binding. + /// Shared by `TDFCBORDecryptor` and `TDFJSONDecryptor`. + static func unwrapSingleSplitECKey( + encryptionInfo: TDFEncryptionInformation, + privateKeyPEM: String, + formatLabel: String, + makeError: (String) -> Error, + ) throws -> SymmetricKey { + let keyAccess = encryptionInfo.keyAccess + guard !keyAccess.isEmpty else { + throw makeError("No key access objects found") + } + + let distinctSplits = Set(keyAccess.map { $0.sid ?? "" }) + guard distinctSplits.count == 1 else { + throw makeError("Split-key \(formatLabel) containers with multiple split IDs are not supported by single-key decrypt") + } + + let ecObjects = keyAccess.filter { $0.type == .ecWrapped } + guard !ecObjects.isEmpty else { + throw makeError("No ec-wrapped key access object found") + } + + var lastError: Error? + for kao in ecObjects { + guard let ephemeralPublicKey = kao.ephemeralPublicKey else { + lastError = makeError("EC-wrapped key missing ephemeral public key") + continue + } + do { + let symmetricKey = try TDFCrypto.unwrapSymmetricKeyWithEC( + privateKeyPEM: privateKeyPEM, + wrappedKey: kao.wrappedKey, + ephemeralPublicKey: ephemeralPublicKey, + ) + guard TDFCrypto.verifyPolicyBinding( + kao.policyBinding, + policyBase64: encryptionInfo.policy, + symmetricKey: symmetricKey, + ) else { + lastError = TDFDecryptError.policyBindingFailed + continue + } + return symmetricKey + } catch { + lastError = error + } + } + throw lastError ?? makeError("Failed to unwrap EC key access object") + } + /// Decrypt a single-split Standard TDF payload with its DEK. /// /// Checks payload algorithm and key size, verifies segment/root integrity and @@ -895,14 +1070,14 @@ public struct TDFDecryptor { } let root = Data(HMAC.authenticationCode(for: Data(signatures.joined()), using: symmetricKey)) guard let manifestRoot = Data(base64Encoded: integrity.rootSignature.sig), - constantTimeEquals(manifestRoot, root) + CryptoHelper.constantTimeEquals(manifestRoot, root) else { throw TDFDecryptError.integrityCheckFailed } for (segment, signature) in zip(integrity.segments, signatures) { guard let manifestHash = Data(base64Encoded: segment.hash), - constantTimeEquals(manifestHash, signature) + CryptoHelper.constantTimeEquals(manifestHash, signature) else { throw TDFDecryptError.integrityCheckFailed } @@ -921,16 +1096,6 @@ public struct TDFDecryptor { throw TDFDecryptError.unsupportedIntegrityAlgorithm(algorithm) } } - - /// Length is public; only the contents are compared in constant time. - private func constantTimeEquals(_ lhs: Data, _ rhs: Data) -> Bool { - guard lhs.count == rhs.count else { return false } - var difference: UInt8 = 0 - for (a, b) in zip(lhs, rhs) { - difference |= a ^ b - } - return difference == 0 - } } /// A configuration `TDFEncryptor` refuses before encrypting. diff --git a/OpenTDFKitTests/GCMEncryptionTests.swift b/OpenTDFKitTests/GCMEncryptionTests.swift index c6552fa..1843e75 100644 --- a/OpenTDFKitTests/GCMEncryptionTests.swift +++ b/OpenTDFKitTests/GCMEncryptionTests.swift @@ -369,10 +369,10 @@ final class GCMEncryptionTests: XCTestCase { } } - func testCryptoSwiftBackedModes() throws { - let cryptoSwiftModes: [Cipher] = [.aes256GCM64, .aes256GCM96, .aes256GCM104, .aes256GCM112, .aes256GCM120] + func testTruncatedTagModes() throws { + let truncatedModes: [Cipher] = [.aes256GCM64, .aes256GCM96, .aes256GCM104, .aes256GCM112, .aes256GCM120] - for cipher in cryptoSwiftModes { + for cipher in truncatedModes { let (ciphertext, tag) = try CryptoHelper.encryptNanoTDF( cipher: cipher, key: testKey, @@ -388,7 +388,7 @@ final class GCMEncryptionTests: XCTestCase { tag: tag, ) - XCTAssertEqual(decrypted, testPlaintext, "CryptoSwift-backed mode \(cipher) should work correctly") + XCTAssertEqual(decrypted, testPlaintext, "Truncated-tag mode \(cipher) should work correctly") } } diff --git a/OpenTDFKitTests/StreamingTDFCryptoTests.swift b/OpenTDFKitTests/StreamingTDFCryptoTests.swift index 1db2826..7aaee55 100644 --- a/OpenTDFKitTests/StreamingTDFCryptoTests.swift +++ b/OpenTDFKitTests/StreamingTDFCryptoTests.swift @@ -127,6 +127,117 @@ final class StreamingTDFCryptoTests: XCTestCase { XCTAssertEqual(try Data(contentsOf: outputURL), plaintext) } + func testEncryptFileStreamingAndDecryptFileRoundTrip() throws { + let plaintext = Data((0 ..< 150_000).map { UInt8($0 & 0xFF) }) + let inputURL = try temporaryFile(data: plaintext) + let archiveURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-tdf-\(UUID().uuidString).tdf") + let outputURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-out-\(UUID().uuidString).bin") + defer { + try? FileManager.default.removeItem(at: inputURL) + try? FileManager.default.removeItem(at: archiveURL) + try? FileManager.default.removeItem(at: outputURL) + } + + let kasKey = P256.KeyAgreement.PrivateKey() + let kas = TDFKasInfo( + url: URL(string: "https://kas.example.com")!, + publicKeyPEM: kasKey.publicKey.pemRepresentation, + kid: "ec-kid-1", + keyType: .ecP256, + ) + let policy = try TDFPolicy(json: Data(#"{"uuid":"1234","body":{"dataAttributes":[]}}"#.utf8)) + let config = TDFEncryptionConfiguration(kas: kas, policy: policy) + + let result = try TDFEncryptor().encryptFileStreaming( + inputURL: inputURL, + outputURL: archiveURL, + configuration: config, + segmentSize: 32768, + ) + XCTAssertEqual(result.manifest.encryptionInformation.integrityInformation?.segments.count, 5) + + try TDFDecryptor().decryptFile( + inputURL: archiveURL, + outputURL: outputURL, + symmetricKey: result.symmetricKey, + chunkSize: 8192, + ) + XCTAssertEqual(try Data(contentsOf: outputURL), plaintext) + } + + func testDecryptFileSinglePassDoesNotCreateOutputOnTamperedRoot() throws { + let plaintext = Data(repeating: 0x42, count: 80000) + let inputURL = try temporaryFile(data: plaintext) + let archiveURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-tamper-\(UUID().uuidString).tdf") + let tamperedArchiveURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-tamper-bad-\(UUID().uuidString).tdf") + let outputURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-tamper-out-\(UUID().uuidString).bin") + defer { + try? FileManager.default.removeItem(at: inputURL) + try? FileManager.default.removeItem(at: archiveURL) + try? FileManager.default.removeItem(at: tamperedArchiveURL) + try? FileManager.default.removeItem(at: outputURL) + } + + let kasKey = P256.KeyAgreement.PrivateKey() + let kas = TDFKasInfo( + url: URL(string: "https://kas.example.com")!, + publicKeyPEM: kasKey.publicKey.pemRepresentation, + kid: "ec-kid-1", + keyType: .ecP256, + ) + let policy = try TDFPolicy(json: Data(#"{"uuid":"1234","body":{"dataAttributes":[]}}"#.utf8)) + let config = TDFEncryptionConfiguration(kas: kas, policy: policy) + + let result = try TDFEncryptor().encryptFileStreaming( + inputURL: inputURL, + outputURL: archiveURL, + configuration: config, + segmentSize: 32768, + ) + + let loaded = try TDFLoader().load(from: archiveURL) + var badManifest = loaded.manifest + badManifest.encryptionInformation.integrityInformation?.rootSignature.sig = Data(repeating: 0, count: 32).base64EncodedString() + try TDFArchiveWriter().buildArchiveToFile(manifest: badManifest, payload: loaded.payload, outputURL: tamperedArchiveURL) + + XCTAssertThrowsError(try TDFDecryptor().decryptFile( + inputURL: tamperedArchiveURL, + outputURL: outputURL, + symmetricKey: result.symmetricKey, + chunkSize: 4096, + )) + XCTAssertFalse(FileManager.default.fileExists(atPath: outputURL.path)) + } + + func testPublicKeyStoreFIFODrainWithCompaction() async throws { + let store = PublicKeyStore(curve: .secp256r1) + let keys = (0 ..< 200).map { i -> Data in + var d = Data(count: 33) + d[0] = 0x02 + d[32] = UInt8(i) + return d + } + await store.addPublicKeys(keys) + + for expected in keys { + let popped = try await store.getAndRemovePublicKey() + XCTAssertEqual(popped, expected) + } + let remaining = await store.publicKeys + XCTAssertTrue(remaining.isEmpty) + do { + _ = try await store.getAndRemovePublicKey() + XCTFail("Expected noKeysAvailable") + } catch PublicKeyStoreError.noKeysAvailable { + // expected + } + } + private func temporaryFile(data: Data) throws -> URL { let url = FileManager.default.temporaryDirectory .appendingPathComponent("streaming-crypto-\(UUID().uuidString)") diff --git a/OpenTDFKitTests/TDFTests.swift b/OpenTDFKitTests/TDFTests.swift index bf040f5..28686b1 100644 --- a/OpenTDFKitTests/TDFTests.swift +++ b/OpenTDFKitTests/TDFTests.swift @@ -1299,4 +1299,46 @@ final class StandardTDFTests: XCTestCase { XCTAssertNil((obj["payload"] as! [String: Any])["tdf_spec_version"]) XCTAssertEqual(obj["schemaVersion"] as? String, "1.0.0") } + + func testAESCBCRoundTripAndEdgeCases() throws { + let keys = [ + SymmetricKey(size: .bits128), + SymmetricKey(size: .bits192), + SymmetricKey(size: .bits256), + ] + let payloads = [ + Data(), + Data("A".utf8), + Data(repeating: 0xAB, count: 16), // exact block boundary (adds full padding block) + Data(repeating: 0xCD, count: 31), + Data(repeating: 0xEF, count: 1024), + ] + + for key in keys { + for plaintext in payloads { + let (iv, ciphertext) = try TDFCrypto.encryptPayloadCBC(plaintext: plaintext, symmetricKey: key) + XCTAssertEqual(iv.count, 16) + XCTAssertGreaterThanOrEqual(ciphertext.count, 16) + XCTAssertEqual(ciphertext.count % 16, 0) + + let decrypted = try TDFCrypto.decryptPayloadCBC(ciphertext: ciphertext, iv: iv, symmetricKey: key) + XCTAssertEqual(decrypted, plaintext) + } + } + + // Invalid IV length rejected + let key256 = SymmetricKey(size: .bits256) + let (iv, ciphertext) = try TDFCrypto.encryptPayloadCBC(plaintext: Data("hello".utf8), symmetricKey: key256) + XCTAssertThrowsError(try TDFCrypto.decryptPayloadCBC(ciphertext: ciphertext, iv: Data(count: 12), symmetricKey: key256)) + + // Unaligned / empty ciphertext rejected + XCTAssertThrowsError(try TDFCrypto.decryptPayloadCBC(ciphertext: Data(), iv: iv, symmetricKey: key256)) + XCTAssertThrowsError(try TDFCrypto.decryptPayloadCBC(ciphertext: Data([1, 2, 3]), iv: iv, symmetricKey: key256)) + + // Corrupted padding deterministically rejected (CBC: P_0 = D_K(C_0) XOR IV, + // so flipping IV[15] turns the final PKCS#7 padding byte 0x0B into 0xF4 > 16). + var tamperedIV = iv + tamperedIV[tamperedIV.count - 1] ^= 0xFF + XCTAssertThrowsError(try TDFCrypto.decryptPayloadCBC(ciphertext: ciphertext, iv: tamperedIV, symmetricKey: key256)) + } } diff --git a/Package.resolved b/Package.resolved index 52ddc43..ed06f80 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,15 +1,6 @@ { - "originHash" : "7391faf16959639b2507781aa5b70a14e3d0ec1f39a6426476e50f099184d650", + "originHash" : "569834272ed7fcca137d5667d6123aa6621ff7f43ed35f10b8e70b27efc766db", "pins" : [ - { - "identity" : "cryptoswift", - "kind" : "remoteSourceControl", - "location" : "https://github.com/krzyzanowskim/CryptoSwift", - "state" : { - "revision" : "f2a627b84c1ff96f21ac2fcb623ab36142dd5512", - "version" : "1.10.0" - } - }, { "identity" : "swiftcbor", "kind" : "remoteSourceControl", diff --git a/Package.swift b/Package.swift index 2fec995..fd6c72b 100644 --- a/Package.swift +++ b/Package.swift @@ -24,7 +24,6 @@ let package = Package( ), ], dependencies: [ - .package(url: "https://github.com/krzyzanowskim/CryptoSwift", from: "1.10.0"), // A version requirement, not a revision: SwiftPM refuses a stable-version // dependency on a package that pins a revision, so a revision here makes // OpenTDFKit unresolvable for every consumer that requires it by version. @@ -35,7 +34,6 @@ let package = Package( .target( name: "OpenTDFKit", dependencies: [ - "CryptoSwift", .product(name: "ZIPFoundation", package: "ZIPFoundation"), .product(name: "SwiftCBOR", package: "SwiftCBOR"), ], From 33d11215b987ae72ed524add3c55f27cebd4c0cb Mon Sep 17 00:00:00 2001 From: Paul Flynn Date: Wed, 25 Nov 2026 19:40:14 -0500 Subject: [PATCH 2/3] fix: bound streaming decryptFile extraction by manifest size and optional maxPayloadSize --- OpenTDFKit/TDF/TDFProcessor.swift | 68 ++++++++++++++++- OpenTDFKitTests/StreamingTDFCryptoTests.swift | 74 +++++++++++++++++++ 2 files changed, 140 insertions(+), 2 deletions(-) diff --git a/OpenTDFKit/TDF/TDFProcessor.swift b/OpenTDFKit/TDF/TDFProcessor.swift index 58fa514..a87b9e8 100644 --- a/OpenTDFKit/TDF/TDFProcessor.swift +++ b/OpenTDFKit/TDF/TDFProcessor.swift @@ -566,11 +566,13 @@ public struct TDFDecryptor { outputURL: URL, symmetricKey: SymmetricKey, chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, + maxPayloadSize: Int? = nil, ) throws { try decryptFileStreaming( inputURL: inputURL, outputURL: outputURL, chunkSize: chunkSize, + maxPayloadSize: maxPayloadSize, resolveKey: { _ in (symmetricKey, false) }, ) } @@ -580,11 +582,13 @@ public struct TDFDecryptor { outputURL: URL, privateKeyPEM: String, chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, + maxPayloadSize: Int? = nil, ) throws { try decryptFileStreaming( inputURL: inputURL, outputURL: outputURL, chunkSize: chunkSize, + maxPayloadSize: maxPayloadSize, resolveKey: { encryptionInfo in let dek = try unwrapDEK(encryptionInformation: encryptionInfo, privateKeyPEM: privateKeyPEM) return (dek, true) @@ -597,19 +601,30 @@ public struct TDFDecryptor { outputURL: URL, symmetricKey: SymmetricKey, chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, + maxPayloadSize: Int? = nil, ) throws { - try decryptFile(inputURL: inputURL, outputURL: outputURL, symmetricKey: symmetricKey, chunkSize: chunkSize) + try decryptFile( + inputURL: inputURL, + outputURL: outputURL, + symmetricKey: symmetricKey, + chunkSize: chunkSize, + maxPayloadSize: maxPayloadSize, + ) } private func decryptFileStreaming( inputURL: URL, outputURL: URL, chunkSize: Int, + maxPayloadSize: Int?, resolveKey: (TDFEncryptionInformation) throws -> (SymmetricKey, Bool), ) throws { guard chunkSize > 0 else { throw StreamingCryptoError.invalidChunkSize } + if let maxPayloadSize, maxPayloadSize < 0 { + throw TDFArchiveError.payloadTooLarge + } let reader = try TDFArchiveReader(url: inputURL) let manifest = try reader.manifest() let encryptionInfo = manifest.encryptionInformation @@ -649,6 +664,26 @@ public struct TDFDecryptor { } } + // Compute an exact upper bound from the manifest when every segment declares an + // encrypted size (or default for non-last segments), using overflow-checked arithmetic. + // This allows streaming payloads larger than `TDFArchiveReader.defaultPayloadMaxSize` + // (512 MiB) while still stopping zip-bomb extraction past the manifest's declared total. + let manifestDeclaredSize = try Self.declaredPayloadSize(for: integrity) + let extractionCap: Int? + switch (maxPayloadSize, manifestDeclaredSize) { + case let (callerCap?, manifestSize?): + guard manifestSize <= callerCap else { + throw TDFArchiveError.payloadTooLarge + } + extractionCap = manifestSize + case let (callerCap?, nil): + extractionCap = callerCap + case let (nil, manifestSize?): + extractionCap = manifestSize + case (nil, nil): + extractionCap = nil + } + // Stream encrypted payload out of ZIP into a private temp file, then decrypt in a single pass. let tempEncryptedURL = outputURL.deletingLastPathComponent() .appendingPathComponent(".\(outputURL.lastPathComponent).\(UUID().uuidString).enc.tmp") @@ -662,7 +697,7 @@ public struct TDFDecryptor { try? FileManager.default.removeItem(at: tempEncryptedURL) } - try reader.writePayload(to: tempHandle) + try reader.writePayload(to: tempHandle, maxSize: extractionCap) let payloadSize = try tempHandle.seekToEnd() try tempHandle.seek(toOffset: 0) @@ -708,6 +743,35 @@ public struct TDFDecryptor { } } + /// Sums the manifest's declared encrypted segment sizes with overflow checking. + /// Returns `nil` only when the final segment omits `encryptedSegmentSize` (whose size + /// defaults to the remaining payload bytes). + private static func declaredPayloadSize(for integrity: TDFIntegrityInformation) throws -> Int? { + var total: Int64 = 0 + for (index, segment) in integrity.segments.enumerated() { + let isLast = index == integrity.segments.count - 1 + let resolvedSize = segment.encryptedSegmentSize ?? (isLast ? nil : integrity.encryptedSegmentSizeDefault) + guard let segmentSize = resolvedSize else { + if isLast { + return nil + } + throw TDFDecryptError.malformedPayload + } + guard segmentSize >= 28 else { + throw TDFDecryptError.malformedPayload + } + let (nextTotal, overflow) = total.addingReportingOverflow(segmentSize) + guard !overflow else { + throw TDFDecryptError.malformedPayload + } + total = nextTotal + } + guard let exact = Int(exactly: total) else { + throw TDFDecryptError.malformedPayload + } + return exact + } + public func decrypt(container: TDFContainer, privateKeyPEM: String) throws -> Data { let symmetricKey = try unwrapDEK( encryptionInformation: container.manifest.encryptionInformation, diff --git a/OpenTDFKitTests/StreamingTDFCryptoTests.swift b/OpenTDFKitTests/StreamingTDFCryptoTests.swift index 7aaee55..74dbcf3 100644 --- a/OpenTDFKitTests/StreamingTDFCryptoTests.swift +++ b/OpenTDFKitTests/StreamingTDFCryptoTests.swift @@ -214,6 +214,80 @@ final class StreamingTDFCryptoTests: XCTestCase { XCTAssertFalse(FileManager.default.fileExists(atPath: outputURL.path)) } + func testDecryptFileHonorsMaxPayloadSizeAndManifestDeclaredBound() throws { + let plaintext = Data((0 ..< 150_000).map { UInt8($0 & 0xFF) }) + let inputURL = try temporaryFile(data: plaintext) + let archiveURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-cap-\(UUID().uuidString).tdf") + let bloatedArchiveURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-bloated-\(UUID().uuidString).tdf") + let outputURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-cap-out-\(UUID().uuidString).bin") + defer { + try? FileManager.default.removeItem(at: inputURL) + try? FileManager.default.removeItem(at: archiveURL) + try? FileManager.default.removeItem(at: bloatedArchiveURL) + try? FileManager.default.removeItem(at: outputURL) + } + + let kasKey = P256.KeyAgreement.PrivateKey() + let kas = TDFKasInfo( + url: URL(string: "https://kas.example.com")!, + publicKeyPEM: kasKey.publicKey.pemRepresentation, + kid: "ec-kid-1", + keyType: .ecP256, + ) + let policy = try TDFPolicy(json: Data(#"{"uuid":"1234","body":{"dataAttributes":[]}}"#.utf8)) + let config = TDFEncryptionConfiguration(kas: kas, policy: policy) + + let result = try TDFEncryptor().encryptFileStreaming( + inputURL: inputURL, + outputURL: archiveURL, + configuration: config, + segmentSize: 32768, + ) + + // Smaller caller-provided maxPayloadSize rejects extraction before writing output + XCTAssertThrowsError(try TDFDecryptor().decryptFile( + inputURL: archiveURL, + outputURL: outputURL, + symmetricKey: result.symmetricKey, + maxPayloadSize: 100_000, + )) { error in + XCTAssertEqual(error as? TDFArchiveError, .payloadTooLarge) + } + XCTAssertFalse(FileManager.default.fileExists(atPath: outputURL.path)) + + // Uncapped default (bounded by manifest's declared segment sum) succeeds + try TDFDecryptor().decryptFile( + inputURL: archiveURL, + outputURL: outputURL, + symmetricKey: result.symmetricKey, + maxPayloadSize: nil, + ) + XCTAssertEqual(try Data(contentsOf: outputURL), plaintext) + try? FileManager.default.removeItem(at: outputURL) + + // Archive whose ZIP payload expands past the manifest's declared segment sum is aborted + // during extraction with payloadTooLarge rather than filling disk. + let loaded = try TDFLoader().load(from: archiveURL) + var bloatedPayload = loaded.payload + bloatedPayload.append(Data(repeating: 0xAA, count: 65536)) + try TDFArchiveWriter().buildArchiveToFile( + manifest: loaded.manifest, + payload: bloatedPayload, + outputURL: bloatedArchiveURL, + ) + XCTAssertThrowsError(try TDFDecryptor().decryptFile( + inputURL: bloatedArchiveURL, + outputURL: outputURL, + symmetricKey: result.symmetricKey, + )) { error in + XCTAssertEqual(error as? TDFArchiveError, .payloadTooLarge) + } + XCTAssertFalse(FileManager.default.fileExists(atPath: outputURL.path)) + } + func testPublicKeyStoreFIFODrainWithCompaction() async throws { let store = PublicKeyStore(curve: .secp256r1) let keys = (0 ..< 200).map { i -> Data in From b6a9a747803aa8869c9a141794dc276aa4edef1b Mon Sep 17 00:00:00 2001 From: Paul Flynn Date: Wed, 25 Nov 2026 19:54:47 -0500 Subject: [PATCH 3/3] fix: address Codex and Claude PR #71 review findings --- OpenTDFKit/KeyStore.swift | 4 +- OpenTDFKit/TDF/StreamingTDFCrypto.swift | 22 ++- OpenTDFKit/TDF/StrictJSON.swift | 17 +- OpenTDFKit/TDF/TDFCBORContainer.swift | 4 +- OpenTDFKit/TDF/TDFCrypto.swift | 18 +- OpenTDFKit/TDF/TDFJSONContainer.swift | 4 +- OpenTDFKit/TDF/TDFKAS.swift | 2 +- OpenTDFKit/TDF/TDFProcessor.swift | 104 +++++++++--- OpenTDFKitTests/StreamingTDFCryptoTests.swift | 158 ++++++++++++++++++ 9 files changed, 278 insertions(+), 55 deletions(-) diff --git a/OpenTDFKit/KeyStore.swift b/OpenTDFKit/KeyStore.swift index b563f55..240ce72 100644 --- a/OpenTDFKit/KeyStore.swift +++ b/OpenTDFKit/KeyStore.swift @@ -88,9 +88,9 @@ public struct EphemeralKeyPair: Sendable { public actor KeyStore { public let curve: Curve - public private(set) var keyPairs: [KeyPairIdentifier: StoredKeyPair] + public var keyPairs: [KeyPairIdentifier: StoredKeyPair] /// Track total memory used - public private(set) var totalBytesStored: Int = 0 + public var totalBytesStored: Int = 0 public init(curve: Curve, capacity: Int = 1000) { self.curve = curve diff --git a/OpenTDFKit/TDF/StreamingTDFCrypto.swift b/OpenTDFKit/TDF/StreamingTDFCrypto.swift index 932bd66..dfd36b2 100644 --- a/OpenTDFKit/TDF/StreamingTDFCrypto.swift +++ b/OpenTDFKit/TDF/StreamingTDFCrypto.swift @@ -463,9 +463,11 @@ public enum StreamingTDFCrypto { /// Single-pass streaming multi-segment decryption directly to `outputURL`. /// Decrypts and verifies each segment's GCM tag and manifest hash into a private (`0600`) - /// staging file beside `outputURL`, then verifies the HS256 root signature before atomically - /// moving the staging file into place. Removes the staging file on any failure, cutting disk - /// I/O and AES-GCM CPU in half compared to two-pass `FileHandle` decryption. + /// staging file beside `outputURL` (peak memory is O(largest segment)), then verifies the + /// HS256 root signature before atomically moving the staging file into place. The parent + /// directory of `outputURL` must be writable, and existing directories at `outputURL` are + /// rejected. Removes the staging file on any failure, cutting disk I/O and AES-GCM CPU in + /// half compared to two-pass `FileHandle` decryption. public static func decryptPayloadStreamingMultiSegment( inputHandle: FileHandle, outputURL: URL, @@ -478,6 +480,11 @@ public enum StreamingTDFCrypto { guard chunkSize > 0 else { throw StreamingCryptoError.invalidChunkSize } guard !segments.isEmpty else { throw StreamingCryptoError.malformedSegment(0) } + var isDir: ObjCBool = false + if FileManager.default.fileExists(atPath: outputURL.path, isDirectory: &isDir), isDir.boolValue { + throw CocoaError(.fileWriteUnknown) + } + let startOffset = try inputHandle.offset() let endOffset = try inputHandle.seekToEnd() guard endOffset >= startOffset else { throw StreamingCryptoError.segmentReadFailed } @@ -487,7 +494,7 @@ public enum StreamingTDFCrypto { .appendingPathComponent(".\(outputURL.lastPathComponent).\(UUID().uuidString).partial") let fd = open(stagingURL.path, O_CREAT | O_EXCL | O_WRONLY, 0o600) guard fd >= 0 else { - throw StreamingCryptoError.segmentReadFailed + throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EACCES) } let stagingHandle = FileHandle(fileDescriptor: fd, closeOnDealloc: false) var stagingClosed = false @@ -556,7 +563,12 @@ public enum StreamingTDFCrypto { let nonce = try AES.GCM.Nonce(data: ivData) let sealed = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertextAccumulator, tag: tagData) - var plaintext = try AES.GCM.open(sealed, using: symmetricKey) + var plaintext: Data + do { + plaintext = try AES.GCM.open(sealed, using: symmetricKey) + } catch { + throw StreamingCryptoError.integrityCheckFailed + } defer { plaintext.secureZero() } try stagingHandle.write(contentsOf: plaintext) diff --git a/OpenTDFKit/TDF/StrictJSON.swift b/OpenTDFKit/TDF/StrictJSON.swift index 6c57b64..9dee996 100644 --- a/OpenTDFKit/TDF/StrictJSON.swift +++ b/OpenTDFKit/TDF/StrictJSON.swift @@ -13,23 +13,22 @@ enum StrictJSON { /// `true` when any object in `data` repeats a member name, or when the /// input can't be scanned. static func hasDuplicateMembers(_ data: Data) -> Bool { - data.withUnsafeBytes { rawBuffer in - let bytes = rawBuffer.bindMemory(to: UInt8.self) - var scanner = Scanner(bytes: bytes) - guard let duplicate = try? scanner.scanValue(depth: 0) else { - return true - } - return duplicate + // Keep bounds-checked `[UInt8]` storage even in `-O` release builds because + // `StrictJSON` scans untrusted Rewrap JWTs (capped at 64 KiB). + var scanner = Scanner(bytes: Array(data)) + guard let duplicate = try? scanner.scanValue(depth: 0) else { + return true } + return duplicate } private struct ScanError: Error {} private struct Scanner { - let bytes: UnsafeBufferPointer + let bytes: [UInt8] var index = 0 - init(bytes: UnsafeBufferPointer) { + init(bytes: [UInt8]) { self.bytes = bytes } diff --git a/OpenTDFKit/TDF/TDFCBORContainer.swift b/OpenTDFKit/TDF/TDFCBORContainer.swift index 4dd72d0..94450f5 100644 --- a/OpenTDFKit/TDF/TDFCBORContainer.swift +++ b/OpenTDFKit/TDF/TDFCBORContainer.swift @@ -300,12 +300,12 @@ public struct TDFCBORDecryptor: Sendable { /// Decrypt a TDF-CBOR container with an EC private key (unwraps the symmetric key first). /// Explicitly rejects split-key containers and non-EC-wrapped key access objects. public func decrypt(container: TDFCBORContainer, privateKeyPEM: String) throws -> Data { - let symmetricKey = try TDFDecryptor.unwrapSingleSplitECKey( + try TDFDecryptor.decryptSingleSplitEC( encryptionInfo: container.encryptionInformation, privateKeyPEM: privateKeyPEM, formatLabel: "TDF-CBOR", makeError: { TDFCBORError.decryptionFailed($0) }, + decryptWithKey: { try decrypt(container: container, symmetricKey: $0) }, ) - return try decrypt(container: container, symmetricKey: symmetricKey) } } diff --git a/OpenTDFKit/TDF/TDFCrypto.swift b/OpenTDFKit/TDF/TDFCrypto.swift index 081dac7..617ece8 100644 --- a/OpenTDFKit/TDF/TDFCrypto.swift +++ b/OpenTDFKit/TDF/TDFCrypto.swift @@ -122,9 +122,11 @@ public enum TDFCrypto { /// Encrypt payload using AES-CBC with PKCS7 padding via hardware-accelerated CommonCrypto. /// This mode is compatible with FairPlay Streaming. + /// - Important: AES-CBC is unauthenticated. Callers must authenticate the IV and ciphertext + /// (e.g., via Encrypt-then-MAC) before calling `decryptPayloadCBC`. /// - Parameters: /// - plaintext: Data to encrypt - /// - symmetricKey: Symmetric key (16 or 32 bytes) + /// - symmetricKey: Symmetric key (16, 24, or 32 bytes) /// - Returns: Tuple of (iv, ciphertext) public static func encryptPayloadCBC(plaintext: Data, symmetricKey: SymmetricKey) throws -> (iv: Data, cipherText: Data) { let bitCount = symmetricKey.bitCount @@ -143,10 +145,12 @@ public enum TDFCrypto { } /// Decrypt payload using AES-CBC with PKCS7 padding via hardware-accelerated CommonCrypto. + /// - Important: AES-CBC is unauthenticated. Callers must verify an authentication tag + /// covering the IV and ciphertext before decryption to prevent padding-oracle attacks. /// - Parameters: /// - ciphertext: Encrypted data /// - iv: Initialization vector (16 bytes) - /// - symmetricKey: Symmetric key (16 or 32 bytes) + /// - symmetricKey: Symmetric key (16, 24, or 32 bytes) /// - Returns: Decrypted plaintext public static func decryptPayloadCBC(ciphertext: Data, iv: Data, symmetricKey: SymmetricKey) throws -> Data { guard iv.count == kCCBlockSizeAES128 else { @@ -175,7 +179,7 @@ public enum TDFCrypto { symmetricKey: SymmetricKey, ) throws -> Data { let isEncrypt = operation == CCOperation(kCCEncrypt) - // Use CommonCrypto PKCS7 padding on encrypt; on decrypt use raw CBC + constant-time + // Use CommonCrypto PKCS7 padding on encrypt; on decrypt use raw CBC + branchless // PKCS7 validation so malformed padding is deterministically rejected across all OS versions. let options: CCOptions = isEncrypt ? CCOptions(kCCOptionPKCS7Padding) : 0 let outputCapacity = isEncrypt ? (input.count + kCCBlockSizeAES128) : input.count @@ -209,7 +213,7 @@ public enum TDFCrypto { if isEncrypt { throw TDFCryptoError.cbcEncryptionFailed("CommonCrypto status \(status)") } else { - throw TDFCryptoError.cbcDecryptionFailed("CommonCrypto status \(status)") + throw TDFCryptoError.cbcDecryptionFailed("Decryption failed") } } @@ -220,10 +224,10 @@ public enum TDFCrypto { guard bytesMoved == input.count, bytesMoved >= kCCBlockSizeAES128 else { output.secureZero() - throw TDFCryptoError.cbcDecryptionFailed("Unexpected decrypted byte count") + throw TDFCryptoError.cbcDecryptionFailed("Decryption failed") } - // Constant-time PKCS7 padding verification over the final 16-byte block. + // Branchless PKCS7 padding check over the final 16-byte block. let padByte = output[bytesMoved - 1] let padLen = Int(padByte) var bad: UInt8 = (padLen >= 1 && padLen <= kCCBlockSizeAES128) ? 0 : 1 @@ -235,7 +239,7 @@ public enum TDFCrypto { } guard bad == 0 else { output.secureZero() - throw TDFCryptoError.cbcDecryptionFailed("Invalid PKCS7 padding") + throw TDFCryptoError.cbcDecryptionFailed("Decryption failed") } output.removeSubrange((bytesMoved - padLen) ..< bytesMoved) diff --git a/OpenTDFKit/TDF/TDFJSONContainer.swift b/OpenTDFKit/TDF/TDFJSONContainer.swift index 98947b0..35fe989 100644 --- a/OpenTDFKit/TDF/TDFJSONContainer.swift +++ b/OpenTDFKit/TDF/TDFJSONContainer.swift @@ -312,12 +312,12 @@ public struct TDFJSONDecryptor: Sendable { /// Decrypt a TDF-JSON container with an EC private key (unwraps the symmetric key first). /// Explicitly rejects split-key manifests and non-EC-wrapped key access objects. public func decrypt(container: TDFJSONContainer, privateKeyPEM: String) throws -> Data { - let symmetricKey = try TDFDecryptor.unwrapSingleSplitECKey( + try TDFDecryptor.decryptSingleSplitEC( encryptionInfo: container.encryptionInformation, privateKeyPEM: privateKeyPEM, formatLabel: "TDF-JSON", makeError: { TDFJSONError.decryptionFailed($0) }, + decryptWithKey: { try decrypt(container: container, symmetricKey: $0) }, ) - return try decrypt(container: container, symmetricKey: symmetricKey) } } diff --git a/OpenTDFKit/TDF/TDFKAS.swift b/OpenTDFKit/TDF/TDFKAS.swift index 54127b1..02b2e80 100644 --- a/OpenTDFKit/TDF/TDFKAS.swift +++ b/OpenTDFKit/TDF/TDFKAS.swift @@ -93,7 +93,7 @@ public enum TDFKAS { let sessionPrivateKey = P256.KeyAgreement.PrivateKey() let sealed = try AES.GCM.seal(share, using: TDFCrypto.deriveKASWrapKey(sessionPrivateKey, receiverPublicKey)) guard let combined = sealed.combined else { - throw TDFKASError.keyUnwrapFailed + throw CryptoKitError.incorrectParameterSize } return RewrapResult(wrappedKey: combined, sessionPublicKey: sessionPrivateKey.publicKey) } diff --git a/OpenTDFKit/TDF/TDFProcessor.swift b/OpenTDFKit/TDF/TDFProcessor.swift index a87b9e8..f47d67e 100644 --- a/OpenTDFKit/TDF/TDFProcessor.swift +++ b/OpenTDFKit/TDF/TDFProcessor.swift @@ -216,6 +216,9 @@ public struct TDFEncryptor { /// Encrypts `inputURL` directly to a TDF archive at `outputURL` using bounded O(segmentSize) /// memory without holding the full encrypted payload in RAM. + /// + /// To decrypt archives whose encrypted payload exceeds `TDFArchiveReader.defaultPayloadMaxSize` + /// (512 MiB), pass an explicit `maxPayloadSize` (or `nil`) to `TDFDecryptor.decryptFile`. public func encryptFileStreaming( inputURL: URL, outputURL: URL, @@ -246,30 +249,63 @@ public struct TDFEncryptor { let inputHandle = try FileHandle(forReadingFrom: inputURL) defer { try? inputHandle.close() } - let streamingResult = try StreamingTDFCrypto.encryptPayloadStreamingMultiSegment( - inputHandle: inputHandle, - outputHandle: tempHandle, - symmetricKey: symmetricKey, - segmentSizes: [segmentSize], - ) + let inputSize = try inputHandle.seekToEnd() + try inputHandle.seek(toOffset: 0) + + let segments: [TDFSegment] + let rawSegmentSigs: [Data] + let firstIV: Data + let lastTag: Data + + if inputSize == 0 { + // Emit one authenticated empty segment so zero-byte files round-trip identically + // to `encryptFile` and in-memory segmented encryption. + let (iv, ciphertext, tag) = try TDFCrypto.encryptPayload(plaintext: Data(), symmetricKey: symmetricKey) + var emptySegmentPayload = Data(capacity: iv.count + ciphertext.count + tag.count) + emptySegmentPayload.append(iv) + emptySegmentPayload.append(ciphertext) + emptySegmentPayload.append(tag) + try tempHandle.write(contentsOf: emptySegmentPayload) + try tempHandle.synchronize() + firstIV = iv + lastTag = tag + rawSegmentSigs = [tag] + segments = [ + TDFSegment( + hash: tag.base64EncodedString(), + segmentSize: 0, + encryptedSegmentSize: Int64(emptySegmentPayload.count), + ), + ] + } else { + let streamingResult = try StreamingTDFCrypto.encryptPayloadStreamingMultiSegment( + inputHandle: inputHandle, + outputHandle: tempHandle, + symmetricKey: symmetricKey, + segmentSizes: [segmentSize], + ) + firstIV = streamingResult.iv + lastTag = streamingResult.tag + segments = streamingResult.segments.map { seg in + TDFSegment( + hash: seg.hash, + segmentSize: seg.plaintextSize, + encryptedSegmentSize: seg.encryptedSize, + ) + } + rawSegmentSigs = segments.compactMap { Data(base64Encoded: $0.hash) } + } + try tempHandle.close() tempHandleClosed = true - let segments = streamingResult.segments.map { seg in - TDFSegment( - hash: seg.hash, - segmentSize: seg.plaintextSize, - encryptedSegmentSize: seg.encryptedSize, - ) - } - let rawSegmentSigs = segments.compactMap { Data(base64Encoded: $0.hash) } let manifest = try makeManifest( segments: segments, rawSegmentSignatures: rawSegmentSigs, segmentSizeDefault: Int64(segmentSize), symmetricKey: symmetricKey, configuration: configuration, - iv: streamingResult.iv, + iv: firstIV, ) try TDFArchiveWriter(compressionMethod: .none) @@ -278,8 +314,8 @@ public struct TDFEncryptor { return TDFStreamingFileEncryptionResult( manifest: manifest, symmetricKey: symmetricKey, - iv: streamingResult.iv, - tag: streamingResult.tag, + iv: firstIV, + tag: lastTag, ) } @@ -561,12 +597,19 @@ public struct TDFStreamingFileEncryptionResult: Sendable { public struct TDFDecryptor { public init() {} + /// Streams a TDF archive from `inputURL` to `outputURL`, authenticating every segment and + /// the root signature before atomically publishing `outputURL` (peak memory is O(largest + /// segment)). Staging uses a private (`0600`) temporary file in `outputURL`'s parent + /// directory, which must be writable; existing directories at `outputURL` are rejected. + /// - Parameter maxPayloadSize: Upper bound on extracted encrypted payload bytes; defaults to + /// `TDFArchiveReader.defaultPayloadMaxSize` (512 MiB) to guard against zip bombs. Pass a + /// higher value or `nil` when decrypting trusted archives over 512 MiB. public func decryptFile( inputURL: URL, outputURL: URL, symmetricKey: SymmetricKey, chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, - maxPayloadSize: Int? = nil, + maxPayloadSize: Int? = TDFArchiveReader.defaultPayloadMaxSize, ) throws { try decryptFileStreaming( inputURL: inputURL, @@ -582,7 +625,7 @@ public struct TDFDecryptor { outputURL: URL, privateKeyPEM: String, chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, - maxPayloadSize: Int? = nil, + maxPayloadSize: Int? = TDFArchiveReader.defaultPayloadMaxSize, ) throws { try decryptFileStreaming( inputURL: inputURL, @@ -601,7 +644,7 @@ public struct TDFDecryptor { outputURL: URL, symmetricKey: SymmetricKey, chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, - maxPayloadSize: Int? = nil, + maxPayloadSize: Int? = TDFArchiveReader.defaultPayloadMaxSize, ) throws { try decryptFile( inputURL: inputURL, @@ -684,12 +727,17 @@ public struct TDFDecryptor { extractionCap = nil } + var isDir: ObjCBool = false + if FileManager.default.fileExists(atPath: outputURL.path, isDirectory: &isDir), isDir.boolValue { + throw CocoaError(.fileWriteUnknown) + } + // Stream encrypted payload out of ZIP into a private temp file, then decrypt in a single pass. let tempEncryptedURL = outputURL.deletingLastPathComponent() .appendingPathComponent(".\(outputURL.lastPathComponent).\(UUID().uuidString).enc.tmp") let fd = open(tempEncryptedURL.path, O_CREAT | O_EXCL | O_RDWR, 0o600) guard fd >= 0 else { - throw StreamingCryptoError.segmentReadFailed + throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EACCES) } let tempHandle = FileHandle(fileDescriptor: fd, closeOnDealloc: false) defer { @@ -738,7 +786,7 @@ public struct TDFDecryptor { ) } catch StreamingCryptoError.integrityCheckFailed { throw TDFDecryptError.integrityCheckFailed - } catch StreamingCryptoError.malformedSegment { + } catch StreamingCryptoError.malformedSegment, StreamingCryptoError.segmentReadFailed { throw TDFDecryptError.malformedPayload } } @@ -950,14 +998,16 @@ public struct TDFDecryptor { return SymmetricKey(data: dek) } - /// Unwraps a single-split EC-wrapped DEK from `encryptionInfo` and verifies its policy binding. - /// Shared by `TDFCBORDecryptor` and `TDFJSONDecryptor`. - static func unwrapSingleSplitECKey( + /// Unwraps and decrypts a single-split EC-wrapped container, trying each same-split + /// EC key access object through policy-binding and payload decryption before falling back + /// to subsequent candidates. Shared by `TDFCBORDecryptor` and `TDFJSONDecryptor`. + static func decryptSingleSplitEC( encryptionInfo: TDFEncryptionInformation, privateKeyPEM: String, formatLabel: String, makeError: (String) -> Error, - ) throws -> SymmetricKey { + decryptWithKey: (SymmetricKey) throws -> Data, + ) throws -> Data { let keyAccess = encryptionInfo.keyAccess guard !keyAccess.isEmpty else { throw makeError("No key access objects found") @@ -993,7 +1043,7 @@ public struct TDFDecryptor { lastError = TDFDecryptError.policyBindingFailed continue } - return symmetricKey + return try decryptWithKey(symmetricKey) } catch { lastError = error } diff --git a/OpenTDFKitTests/StreamingTDFCryptoTests.swift b/OpenTDFKitTests/StreamingTDFCryptoTests.swift index 74dbcf3..a8f2a0c 100644 --- a/OpenTDFKitTests/StreamingTDFCryptoTests.swift +++ b/OpenTDFKitTests/StreamingTDFCryptoTests.swift @@ -288,6 +288,164 @@ final class StreamingTDFCryptoTests: XCTestCase { XCTAssertFalse(FileManager.default.fileExists(atPath: outputURL.path)) } + func testEncryptFileStreamingSupportsEmptyInput() throws { + let inputURL = try temporaryFile(data: Data()) + let archiveURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-empty-\(UUID().uuidString).tdf") + let outputURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-empty-out-\(UUID().uuidString).bin") + defer { + try? FileManager.default.removeItem(at: inputURL) + try? FileManager.default.removeItem(at: archiveURL) + try? FileManager.default.removeItem(at: outputURL) + } + + let kasKey = P256.KeyAgreement.PrivateKey() + let kas = TDFKasInfo( + url: URL(string: "https://kas.example.com")!, + publicKeyPEM: kasKey.publicKey.pemRepresentation, + kid: "ec-kid-empty", + keyType: .ecP256, + ) + let policy = try TDFPolicy(json: Data(#"{"uuid":"1234","body":{"dataAttributes":[]}}"#.utf8)) + let config = TDFEncryptionConfiguration(kas: kas, policy: policy) + + let result = try TDFEncryptor().encryptFileStreaming( + inputURL: inputURL, + outputURL: archiveURL, + configuration: config, + segmentSize: 32768, + ) + XCTAssertEqual(result.manifest.encryptionInformation.integrityInformation?.segments.count, 1) + XCTAssertEqual(result.manifest.encryptionInformation.integrityInformation?.segments.first?.segmentSize, 0) + + try TDFDecryptor().decryptFile( + inputURL: archiveURL, + outputURL: outputURL, + symmetricKey: result.symmetricKey, + ) + XCTAssertEqual(try Data(contentsOf: outputURL), Data()) + } + + func testECContainerDecryptFallsBackAcrossSameSplitKAOs() throws { + let kasKey = P256.KeyAgreement.PrivateKey() + let policy = try TDFPolicy(json: Data(#"{"uuid":"fallback-test","body":{"dataAttributes":[]}}"#.utf8)) + let plaintext = Data("secret payload".utf8) + let kasURL = URL(string: "https://kas.example.com")! + + // Build a valid TDF-JSON container, then prepend a decoy KAO wrapped to the same + // recipient & policy with a different DEK (so unwrap + policyBinding succeed, + // but payload decryption must fall through to the second KAO). + let validResult = try TDFJSONBuilder() + .kasURL(kasURL) + .kasPublicKey(kasKey.publicKey.pemRepresentation) + .policy(policy) + .encrypt(plaintext: plaintext) + + let wrongDEK = SymmetricKey(size: .bits256) + let decoyWrap = try TDFCrypto.wrapSymmetricKeyWithEC( + publicKeyPEM: kasKey.publicKey.pemRepresentation, + symmetricKey: wrongDEK, + ) + let decoyKAO = TDFKeyAccessObject( + type: .ecWrapped, + url: kasURL.absoluteString, + protocolValue: .kas, + wrappedKey: decoyWrap.wrappedKey, + policyBinding: TDFCrypto.policyBinding(policy: policy.json, symmetricKey: wrongDEK), + kid: nil, + sid: nil, + schemaVersion: "1.0", + ephemeralPublicKey: decoyWrap.ephemeralPublicKey, + ) + + var encInfo = validResult.container.encryptionInformation + encInfo.keyAccess = [decoyKAO] + encInfo.keyAccess + let modifiedEnvelope = TDFJSONEnvelope( + tdf: validResult.container.envelope.tdf, + version: validResult.container.envelope.version, + created: validResult.container.envelope.created, + manifest: TDFJSONManifest(encryptionInformation: encInfo, assertions: nil), + payload: validResult.container.envelope.payload, + ) + let modifiedContainer = TDFJSONContainer( + envelope: modifiedEnvelope, + payloadData: validResult.container.payloadData, + ) + + let recovered = try TDFJSONDecryptor().decrypt( + container: modifiedContainer, + privateKeyPEM: kasKey.pemRepresentation, + ) + XCTAssertEqual(recovered, plaintext) + } + + func testDecryptFileTamperedCiphertextThrowsIntegrityCheckFailedAndRejectsDirectoryOutput() throws { + let plaintext = Data(repeating: 0x55, count: 40000) + let inputURL = try temporaryFile(data: plaintext) + let archiveURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-ct-src-\(UUID().uuidString).tdf") + let tamperedArchiveURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-ct-bad-\(UUID().uuidString).tdf") + let outputURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-ct-out-\(UUID().uuidString).bin") + let existingDirURL = FileManager.default.temporaryDirectory + .appendingPathComponent("streaming-dir-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: existingDirURL, withIntermediateDirectories: true) + defer { + try? FileManager.default.removeItem(at: inputURL) + try? FileManager.default.removeItem(at: archiveURL) + try? FileManager.default.removeItem(at: tamperedArchiveURL) + try? FileManager.default.removeItem(at: outputURL) + try? FileManager.default.removeItem(at: existingDirURL) + } + + let kasKey = P256.KeyAgreement.PrivateKey() + let kas = TDFKasInfo( + url: URL(string: "https://kas.example.com")!, + publicKeyPEM: kasKey.publicKey.pemRepresentation, + kid: "ec-kid-ct", + keyType: .ecP256, + ) + let policy = try TDFPolicy(json: Data(#"{"uuid":"ct-tamper","body":{"dataAttributes":[]}}"#.utf8)) + let config = TDFEncryptionConfiguration(kas: kas, policy: policy) + + let result = try TDFEncryptor().encryptFileStreaming( + inputURL: inputURL, + outputURL: archiveURL, + configuration: config, + segmentSize: 16384, + ) + + // Flip a ciphertext byte (leaving GMAC tag intact so AES.GCM.open catches it) + let loaded = try TDFLoader().load(from: archiveURL) + var tamperedPayload = loaded.payload + tamperedPayload[12] ^= 0x01 + try TDFArchiveWriter().buildArchiveToFile( + manifest: loaded.manifest, + payload: tamperedPayload, + outputURL: tamperedArchiveURL, + ) + + XCTAssertThrowsError(try TDFDecryptor().decryptFile( + inputURL: tamperedArchiveURL, + outputURL: outputURL, + symmetricKey: result.symmetricKey, + )) { error in + XCTAssertEqual(error as? TDFDecryptError, .integrityCheckFailed) + } + XCTAssertFalse(FileManager.default.fileExists(atPath: outputURL.path)) + + // Reject existing directory as outputURL without touching it + XCTAssertThrowsError(try TDFDecryptor().decryptFile( + inputURL: archiveURL, + outputURL: existingDirURL, + symmetricKey: result.symmetricKey, + )) + var isDir: ObjCBool = false + XCTAssertTrue(FileManager.default.fileExists(atPath: existingDirURL.path, isDirectory: &isDir) && isDir.boolValue) + } + func testPublicKeyStoreFIFODrainWithCompaction() async throws { let store = PublicKeyStore(curve: .secp256r1) let keys = (0 ..< 200).map { i -> Data in