From c8a2e20fc6ad3495d1702484c68e40aeed724f1b Mon Sep 17 00:00:00 2001 From: Paul Flynn Date: Sun, 22 Nov 2026 18:41:41 -0500 Subject: [PATCH 1/3] fix: address remaining 34 security and bug findings from #69 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolves all 34 open and partially-fixed findings from the v5.1.0 security and bug audit in #69 (4 of the 38 findings — #3, #18, #28, #36 — were already resolved in PR #65): - NanoTDF crypto & parsing (#1, #2, #4, #5, #6, #7, #12, #20, #21, #22, #33): - Domain-separated HKDF policy key + appended 16-byte GCM tag for .embeddedEncrypted and .embeddedEncryptedWithPolicyKeyAccess (fixes nonce reuse and plaintext fallback in NanoTDFCollectionBuilder). - Non-zero IV generation; reject non-P256 curves in addSignatureToNanoTDF; enforce policy binding verification on decrypt; v12 KeyStore resolution for parsed headers; constant-time CoreCrypto CTR+GCM for truncated tags (removing CryptoSwift.GCM); startIndex/overflow-safe BinaryParser & collection parser; strict identifierType/PolicyKeyAccess checks; restore ProtocolEnum.sharedResourceDirectory wire mapping (0x0F). - KAS discovery, transport, rewrap & KeyStore (#8, #9, #10, #11, #23, #24, #25, #26, #32, #34, #35): - Harden validateKasURL against non-canonical IPv4 (octal/hex/int/short), userinfo, IPv6 zone IDs, and reserved CIDRs (0/8, 100.64/10, 224/4, 240/4, ::ffff:0:0/96, NAT64, fec0::/10, ff00::/8). - BoundedHTTPClient (no redirects, response byte cap) for well-known, KASService, and URLSessionKASTransport; no raw server bodies in errors; preserve explicit kas endpoints when kas.uri is empty. - Atomic popPrivateKey + deterministic key IDs in KASService; multi-curve P-256/P-384/P-521 NanoTDF rewrap with client-key JWT signing & remote policy encoding; strict KAO ID validation and numeric share sorting. - Secure zeroing of key material in KeyStore & bulk rewrap, accurate totalBytesStored tracking, and atomic PublicKeyStore.deserialize. - Standard TDF, JSON/CBOR & streaming (#13, #14, #15, #16, #17, #19, #27, #29, #30, #31, #37, #38): - Policy binding verification (spec raw + legacy hex) and symmetric key bit-count validation across Archive, JSON, and CBOR decryptors; explicit rejection of multi-split JSON/CBOR manifests. - Per-segment hash & optional rootSignature verification with buffered output in StreamingTDFCrypto; overflow-safe chunking & bounded archive payload reads; multi-curve EC unwrap; zeroing of intermediate key copies. - Iterative depth/size-bounded CBOR pre-validator; startIndex-safe magic check; PEM ephemeralPublicKey, encryptedMetadata & sid round-tripping; accurate CBOR format detection and bounded JSON file probing. Adds SecurityAuditRegressionTests covering all 34 findings. Closes #69 --- OpenTDFKit/BinaryParser.swift | 43 +- OpenTDFKit/CryptoHelper.swift | 233 ++-- OpenTDFKit/KASBulkRewrap.swift | 5 +- OpenTDFKit/KASDiscovery.swift | 345 +++++- OpenTDFKit/KASRewrapClient.swift | 258 ++-- OpenTDFKit/KASService.swift | 125 +- OpenTDFKit/KeyStore.swift | 151 ++- OpenTDFKit/NanoTDF.swift | 189 ++- OpenTDFKit/NanoTDFCollectionBuilder.swift | 91 +- OpenTDFKit/NanoTDFCollectionDecryptor.swift | 38 +- OpenTDFKit/NanoTDFCollectionParser.swift | 24 +- OpenTDFKit/PublicKeyStore.swift | 22 +- OpenTDFKit/TDF/StreamingTDFCrypto.swift | 94 +- OpenTDFKit/TDF/TDFArchive.swift | 68 +- OpenTDFKit/TDF/TDFBuilder.swift | 4 +- OpenTDFKit/TDF/TDFCBORContainer.swift | 56 +- OpenTDFKit/TDF/TDFCBORFormat.swift | 685 +++++++---- OpenTDFKit/TDF/TDFCrypto.swift | 187 ++- OpenTDFKit/TDF/TDFFormatDetector.swift | 48 +- OpenTDFKit/TDF/TDFJSONContainer.swift | 61 +- OpenTDFKit/TDF/TDFJSONFormat.swift | 14 +- OpenTDFKit/TDF/TDFProcessor.swift | 138 ++- OpenTDFKitTests/KASDiscoveryTests.swift | 29 +- .../SecurityAuditRegressionTests.swift | 1073 +++++++++++++++++ 24 files changed, 3243 insertions(+), 738 deletions(-) create mode 100644 OpenTDFKitTests/SecurityAuditRegressionTests.swift diff --git a/OpenTDFKit/BinaryParser.swift b/OpenTDFKit/BinaryParser.swift index ca199d6..32704c8 100644 --- a/OpenTDFKit/BinaryParser.swift +++ b/OpenTDFKit/BinaryParser.swift @@ -9,11 +9,14 @@ public class BinaryParser { } func read(length: Int) -> Data? { - guard length >= 0, cursor >= 0, cursor + length <= data.count else { return nil } - let range = cursor ..< (cursor + length) + guard length >= 0, cursor >= 0, cursor <= data.count, length <= data.count - cursor else { + return nil + } + let start = data.startIndex + cursor + let end = start + length cursor += length // Use zero-copy slicing instead of subdata to avoid allocations - return data[range] + return data[start ..< end] } @inline(__always) @@ -31,8 +34,13 @@ public class BinaryParser { let protocolValue = protocolByte & 0x0F let identifierType = (protocolByte >> 4) & 0x0F - // Get the protocol enum - guard let protocolEnumValue = ProtocolEnum(rawValue: protocolValue) else { + // Get the protocol enum (0x0F maps to sharedResourceDirectory, which has rawValue 0xFF) + let protocolEnumValue: ProtocolEnum + if protocolValue == 0x0F { + protocolEnumValue = .sharedResourceDirectory + } else if let parsedProtocol = ProtocolEnum(rawValue: protocolValue) { + protocolEnumValue = parsedProtocol + } else { return nil } @@ -44,9 +52,16 @@ public class BinaryParser { return nil } - // Read identifier if present - let identifierSizes: [UInt8: Int] = [0: 0, 1: 2, 2: 8, 3: 32] - let identifierSize = identifierSizes[identifierType] ?? 0 + // Read identifier if present (only identifier types 0...3 are valid per spec 3.4.1.1) + let identifierSize: Int + switch identifierType { + case 0: identifierSize = 0 + case 1: identifierSize = 2 + case 2: identifierSize = 8 + case 3: identifierSize = 32 + default: + return nil + } var identifier: Data? = nil if identifierSize > 0 { @@ -104,8 +119,16 @@ public class BinaryParser { guard let plaintextCiphertext = read(length: Int(contentLength)) else { throw ParsingError.invalidPolicy } - // Policy Key Access - let keyAccess = policyType == .embeddedEncryptedWithPolicyKeyAccess ? readPolicyKeyAccess(bindingMode: bindingMode) : nil + // Policy Key Access (required when policyType is .embeddedEncryptedWithPolicyKeyAccess) + let keyAccess: PolicyKeyAccess? + if policyType == .embeddedEncryptedWithPolicyKeyAccess { + guard let parsedKeyAccess = readPolicyKeyAccess(bindingMode: bindingMode) else { + throw ParsingError.invalidPolicy + } + keyAccess = parsedKeyAccess + } else { + keyAccess = nil + } return EmbeddedPolicyBody(body: plaintextCiphertext, keyAccess: keyAccess) } diff --git a/OpenTDFKit/CryptoHelper.swift b/OpenTDFKit/CryptoHelper.swift index b12f33c..02f60d1 100644 --- a/OpenTDFKit/CryptoHelper.swift +++ b/OpenTDFKit/CryptoHelper.swift @@ -1,5 +1,5 @@ +import CommonCrypto import CryptoKit -import CryptoSwift import Foundation /// Enum representing the KAS key curves supported for NanoTDF Payload Key Access. @@ -247,6 +247,75 @@ public actor CryptoHelper { return nonce } + /// Generates a cryptographically secure non-zero random nonce of the specified length. + /// Guarantees the generated bytes are not all zero (required for NanoTDF payloads because + /// nonce `0x000000` is reserved for GMAC binding / policy operations). + nonisolated func generateNonZeroNonce(length: Int = CryptoConstants.nanoTDFNonceSize) throws -> Data { + guard length > 0 else { + throw CryptoHelperError.keyGenerationFailed + } + for _ in 0 ..< 16 { + let candidate = try generateNonce(length: length) + if candidate.contains(where: { $0 != 0 }) { + return candidate + } + } + throw CryptoHelperError.keyGenerationFailed + } + + /// Derives a domain-separated symmetric key for NanoTDF `.embeddedEncrypted` policy + /// encryption from the payload symmetric key. This guarantees key separation between + /// policy encryption (which uses zero IV) and GMAC policy binding (which uses zero IV + /// with the payload symmetric key), preventing AES-GCM nonce reuse. + public static func deriveEmbeddedPolicyKey(from symmetricKey: SymmetricKey) -> SymmetricKey { + HKDF.deriveKey( + inputKeyMaterial: symmetricKey, + salt: CryptoConstants.hkdfSaltV12, + info: Data("nanotdf-embedded-policy".utf8), + outputByteCount: CryptoConstants.symmetricKeyByteCount, + ) + } + + /// Encrypts an embedded policy using a domain-separated key derived from `symmetricKey` + /// and zero IV, returning `ciphertext || tag` (with 16-byte GCM authentication tag). + public static func encryptEmbeddedPolicy(plaintext: Data, using symmetricKey: SymmetricKey) throws -> Data { + let policyKey = deriveEmbeddedPolicyKey(from: symmetricKey) + let nonce = try CryptoKit.AES.GCM.Nonce(data: Data(count: CryptoConstants.aesGcmNonceSize)) + let sealed = try CryptoKit.AES.GCM.seal(plaintext, using: policyKey, nonce: nonce) + var combined = Data(capacity: sealed.ciphertext.count + sealed.tag.count) + combined.append(sealed.ciphertext) + combined.append(sealed.tag) + return combined + } + + /// Decrypts and authenticates an embedded policy encrypted by `encryptEmbeddedPolicy`. + /// Expects `ciphertext || tag` with a 16-byte GCM authentication tag. + public static func decryptEmbeddedPolicy(ciphertextWithTag: Data, using symmetricKey: SymmetricKey) throws -> Data { + let tagSize = CryptoConstants.aesGcmTagSize + guard ciphertextWithTag.count >= tagSize else { + throw CryptoKitError.authenticationFailure + } + let policyKey = deriveEmbeddedPolicyKey(from: symmetricKey) + let nonce = try CryptoKit.AES.GCM.Nonce(data: Data(count: CryptoConstants.aesGcmNonceSize)) + let split = ciphertextWithTag.index(ciphertextWithTag.endIndex, offsetBy: -tagSize) + let sealedBox = try CryptoKit.AES.GCM.SealedBox( + nonce: nonce, + ciphertext: ciphertextWithTag[ciphertextWithTag.startIndex ..< split], + tag: ciphertextWithTag[split ..< ciphertextWithTag.endIndex], + ) + return try CryptoKit.AES.GCM.open(sealedBox, using: policyKey) + } + + /// Constant-time comparison of two byte sequences. Length comparison is not secret. + static func constantTimeEquals(_ lhs: Data, _ rhs: Data) -> Bool { + guard lhs.count == rhs.count else { return false } + var diff: UInt8 = 0 + for (a, b) in zip(lhs, rhs) { + diff |= a ^ b + } + return diff == 0 + } + /// Adjusts a nonce to a specific length required by a cryptographic algorithm (e.g., AES-GCM typically needs 12 bytes). /// - If the input nonce is the correct length, it's returned unchanged. /// - If it's longer, it's truncated. @@ -385,8 +454,7 @@ public actor CryptoHelper { } // Validate key size (must be 32 bytes for AES-256) - let keyData = key.withUnsafeBytes { Data($0) } - guard keyData.count == 32 else { + guard key.bitCount == 256 else { throw CryptoHelperError.keyDerivationFailed } @@ -395,9 +463,10 @@ public actor CryptoHelper { throw CryptoHelperError.keyDerivationFailed } - // For 128-bit tags, use CryptoKit (it's faster) + let nonce = try CryptoKit.AES.GCM.Nonce(data: iv) + + // For 128-bit tags, open directly with CryptoKit. if cipher == .aes256GCM128 { - let nonce = try CryptoKit.AES.GCM.Nonce(data: iv) let sealedBox = try CryptoKit.AES.GCM.SealedBox( nonce: nonce, ciphertext: ciphertext, @@ -406,14 +475,22 @@ public actor CryptoHelper { return try CryptoKit.AES.GCM.open(sealedBox, using: key) } - // For all other tag sizes, use CryptoSwift - return try decryptWithCryptoSwift( - key: keyData, - iv: iv, - ciphertext: ciphertext, - tag: tag, - tagLength: expectedTagSize, + // For truncated GCM tags (64/96/104/112/120 bits), decrypt via hardware-accelerated + // constant-time CommonCrypto AES-CTR starting at inc_32(J0) = IV || 0x00000002, + // recompute the full 128-bit GCM tag via CryptoKit, and verify the truncated prefix + // in constant time before releasing plaintext. + var candidatePlaintext = try aesCTRTransform( + key: key, + iv12: iv, + input: ciphertext, ) + let sealed = try CryptoKit.AES.GCM.seal(candidatePlaintext, using: key, nonce: nonce) + let expectedTag = Data(sealed.tag.prefix(expectedTagSize)) + guard constantTimeEquals(tag, expectedTag) else { + candidatePlaintext.secureZero() + throw CryptoKitError.authenticationFailure + } + return candidatePlaintext } /// Encrypt NanoTDF payload using the appropriate GCM implementation based on tag size @@ -430,8 +507,7 @@ public actor CryptoHelper { plaintext: Data, ) throws -> (ciphertext: Data, tag: Data) { // Validate key size - let keyData = key.withUnsafeBytes { Data($0) } - guard keyData.count == 32 else { + guard key.bitCount == 256 else { throw CryptoHelperError.keyDerivationFailed } @@ -440,20 +516,15 @@ public actor CryptoHelper { throw CryptoHelperError.keyDerivationFailed } - // For 128-bit tags, use CryptoKit - if cipher == .aes256GCM128 { - let nonce = try CryptoKit.AES.GCM.Nonce(data: iv) - let sealedBox = try CryptoKit.AES.GCM.seal(plaintext, using: key, nonce: nonce) + // Per NIST SP 800-38D §7.1, a t-bit GCM tag is the leftmost t bits of the + // 128-bit GCM tag, with identical ciphertext for all tag lengths. + let nonce = try CryptoKit.AES.GCM.Nonce(data: iv) + let sealedBox = try CryptoKit.AES.GCM.seal(plaintext, using: key, nonce: nonce) + let expectedTagSize = tagSize(for: cipher) + if expectedTagSize == 16 { return (sealedBox.ciphertext, sealedBox.tag) } - - // For all other tag sizes, use CryptoSwift - return try encryptWithCryptoSwift( - key: keyData, - iv: iv, - plaintext: plaintext, - tagLength: tagSize(for: cipher), - ) + return (sealedBox.ciphertext, Data(sealedBox.tag.prefix(expectedTagSize))) } /// Get the tag size in bytes for a given NanoTDF cipher @@ -468,71 +539,67 @@ public actor CryptoHelper { } } - // MARK: - CryptoSwift Implementation + // MARK: - Constant-Time AES-CTR Helper (CommonCrypto) - private static func decryptWithCryptoSwift( - key: Data, - iv: Data, - ciphertext: Data, - tag: Data, - tagLength: Int, + private static func aesCTRTransform( + key: SymmetricKey, + iv12: Data, + input: Data, ) throws -> Data { - guard key.count == 32, iv.count == 12 else { + guard iv12.count == 12 else { throw CryptoHelperError.keyDerivationFailed } + if input.isEmpty { + return Data() + } - // Configure GCM with the specific tag length - let gcm = CryptoSwift.GCM( - iv: Array(iv), - additionalAuthenticatedData: nil, - tagLength: tagLength, - ) - - // IMPORTANT: Set the authentication tag for decryption (detached tag model) - gcm.authenticationTag = Array(tag) - - let aes = try CryptoSwift.AES( - key: Array(key), - blockMode: gcm, - padding: .noPadding, - ) - - // Decrypt just the ciphertext (NOT combined with tag) - let plaintextBytes = try aes.decrypt(Array(ciphertext)) - return Data(plaintextBytes) - } - - private static func encryptWithCryptoSwift( - key: Data, - iv: Data, - plaintext: Data, - tagLength: Int, - ) throws -> (ciphertext: Data, tag: Data) { - guard key.count == 32, iv.count == 12 else { + // Initial counter block for GCM GCTR encryption/decryption: IV (12 bytes) || 0x00000002 + var counterBlock = Data(capacity: 16) + counterBlock.append(iv12) + counterBlock.append(contentsOf: [0x00, 0x00, 0x00, 0x02]) + + var cryptor: CCCryptorRef? + let createStatus: CCCryptorStatus = key.withUnsafeBytes { keyBytes in + counterBlock.withUnsafeBytes { ivBytes in + CCCryptorCreateWithMode( + CCOperation(kCCDecrypt), + CCMode(kCCModeCTR), + CCAlgorithm(kCCAlgorithmAES), + CCPadding(ccNoPadding), + ivBytes.baseAddress, + keyBytes.baseAddress, + keyBytes.count, + nil, + 0, + 0, + CCModeOptions(kCCModeOptionCTR_BE), + &cryptor, + ) + } + } + guard createStatus == kCCSuccess, let cryptor else { throw CryptoHelperError.keyDerivationFailed } - - // Configure GCM with the specific tag length - let gcm = CryptoSwift.GCM( - iv: Array(iv), - additionalAuthenticatedData: nil, - tagLength: tagLength, - ) - - let aes = try CryptoSwift.AES( - key: Array(key), - blockMode: gcm, - padding: .noPadding, - ) - - // CryptoSwift returns just the ciphertext (same length as plaintext) - let ciphertextBytes = try aes.encrypt(Array(plaintext)) - - // Get the authentication tag separately (detached tag model) - guard let tagBytes = gcm.authenticationTag else { + defer { CCCryptorRelease(cryptor) } + + var output = Data(count: input.count) + var bytesMoved = 0 + let updateStatus: CCCryptorStatus = input.withUnsafeBytes { inBytes in + output.withUnsafeMutableBytes { outBytes in + CCCryptorUpdate( + cryptor, + inBytes.baseAddress, + input.count, + outBytes.baseAddress, + outBytes.count, + &bytesMoved, + ) + } + } + guard updateStatus == kCCSuccess, bytesMoved == input.count else { + output.secureZero() throw CryptoHelperError.keyDerivationFailed } - - return (Data(ciphertextBytes), Data(tagBytes)) + return output } } diff --git a/OpenTDFKit/KASBulkRewrap.swift b/OpenTDFKit/KASBulkRewrap.swift index fa07003..81e3dfb 100644 --- a/OpenTDFKit/KASBulkRewrap.swift +++ b/OpenTDFKit/KASBulkRewrap.swift @@ -349,9 +349,12 @@ extension KASRewrapClient { if let sessionKEK, let wrappedBase64 = result.kasWrappedKey ?? result.entityWrappedKey, let wrapped = Data(base64Encoded: wrappedBase64), + wrapped.count > 28, let sealed = try? AES.GCM.SealedBox(combined: wrapped), - let dek = try? AES.GCM.open(sealed, using: sessionKEK) + var dek = try? AES.GCM.open(sealed, using: sessionKEK), + !dek.isEmpty { + defer { dek.secureZero() } return .permitted(SymmetricKey(data: dek)) } unwrapFailed = true diff --git a/OpenTDFKit/KASDiscovery.swift b/OpenTDFKit/KASDiscovery.swift index 18c1890..a86f561 100644 --- a/OpenTDFKit/KASDiscovery.swift +++ b/OpenTDFKit/KASDiscovery.swift @@ -92,17 +92,20 @@ public struct OpenTDFConfiguration: Codable, Sendable { ) } - /// True when well-known has no kas block, an empty kas uri, or advertises - /// neither Connect nor REST endpoint pairs. False when endpoint URLs are - /// present (even if they would fail later SSRF/scheme validation). + /// True when well-known has no kas block or advertises no endpoint URLs at + /// all. False whenever any endpoint URL is present (even if `kas.uri` is + /// empty or an endpoint would fail later SSRF/scheme validation), so hostile + /// or misconfigured kas blocks are never silently overridden. var needsKasEndpointSynthesis: Bool { guard let kas else { return true } - if kas.uri.isEmpty { - return true + let hasAnyEndpoint = kas.connectRewrapURL != nil + || kas.connectPublicKeyURL != nil + || kas.rewrapURL != nil + || kas.publicKeyURL != nil + if hasAnyEndpoint { + return false } - let hasConnect = kas.connectRewrapURL != nil && kas.connectPublicKeyURL != nil - let hasRest = kas.rewrapURL != nil && kas.publicKeyURL != nil - return !hasConnect && !hasRest + return true } } @@ -212,25 +215,97 @@ private enum IPLiteral { case v6([UInt8]) // 16 bytes, network order } +private func stripIPv6Brackets(_ host: String) -> String { + if host.hasPrefix("["), host.hasSuffix("]"), host.count >= 2 { + return String(host.dropFirst().dropLast()) + } + return host +} + +private func isNonCanonicalIPv4Literal(_ host: String) -> Bool { + let trimmed = host.hasSuffix(".") ? String(host.dropLast()) : host + guard !trimmed.isEmpty else { return false } + // IPv6 literals contain colons and are validated by classifyIP. + if trimmed.contains(":") { + return false + } + + // Check dot-separated numeric forms explicitly before inet_pton because + // some parsers accept leading zeros (octal ambiguity) or normalize forms. + let parts = trimmed.split(separator: ".", omittingEmptySubsequences: false) + if (1 ... 4).contains(parts.count), parts.allSatisfy({ part in + guard !part.isEmpty else { return false } + if part.hasPrefix("0x") || part.hasPrefix("0X") { + let digits = part.dropFirst(2) + return !digits.isEmpty && digits.allSatisfy(\.isHexDigit) + } + return part.allSatisfy { $0.isASCII && $0.isNumber } + }) { + // Canonical IPv4 requires exactly 4 decimal octets in 0...255 with no leading zeros. + let isCanonicalV4 = parts.count == 4 && parts.allSatisfy { part in + if part.count > 1, part.hasPrefix("0") { + return false + } + return UInt8(part) != nil + } + return !isCanonicalV4 + } + + // If BSD inet_aton accepts a host that strict inet_pton rejected, it is a + // non-canonical numeric IPv4 form. + var v4 = in_addr() + if trimmed.withCString({ inet_pton(AF_INET, $0, &v4) }) == 1 { + return false + } + var legacy = in_addr() + if trimmed.withCString({ inet_aton($0, &legacy) }) != 0 { + return true + } + return false +} + +/// Extracts the unnormalized host portion from a URL string's authority so +/// non-canonical numeric forms (like octal IPv4) are caught even if Foundation +/// normalizes `url.host`. +private func rawAuthorityHost(from urlString: String) -> String? { + guard let schemeEnd = urlString.range(of: "://") else { return nil } + let afterScheme = urlString[schemeEnd.upperBound...] + let authorityEnd = afterScheme.firstIndex { $0 == "/" || $0 == "?" || $0 == "#" } ?? afterScheme.endIndex + var authority = afterScheme[.. IPLiteral? { + let normalized = stripIPv6Brackets(host) var v4 = in_addr() - if host.withCString({ inet_pton(AF_INET, $0, &v4) }) == 1 { + if normalized.withCString({ inet_pton(AF_INET, $0, &v4) }) == 1 { return .v4(withUnsafeBytes(of: v4.s_addr) { Array($0) }) } var v6 = in6_addr() - if host.withCString({ inet_pton(AF_INET6, $0, &v6) }) == 1 { + if normalized.withCString({ inet_pton(AF_INET6, $0, &v6) }) == 1 { return .v6(withUnsafeBytes(of: v6) { Array($0) }) } return nil } private func isLoopbackHost(_ host: String) -> Bool { - // Normalize a trailing FQDN dot ("localhost." resolves to loopback too). - let host = host.hasSuffix(".") ? String(host.dropLast()) : host - if host == "localhost" { + // Normalize case and trailing FQDN dot ("LOCALHOST." resolves to loopback too). + let stripped = stripIPv6Brackets(host).lowercased() + let normalized = stripped.hasSuffix(".") ? String(stripped.dropLast()) : stripped + if normalized == "localhost" { return true } - switch classifyIP(host) { + switch classifyIP(normalized) { case let .v4(o): return o[0] == 127 // 127.0.0.0/8 case let .v6(b): return b.dropLast() == ArraySlice(repeating: 0, count: 15) && b[15] == 1 // ::1 case .none: return false @@ -238,24 +313,32 @@ private func isLoopbackHost(_ host: String) -> Bool { } private func isBlockedV4(_ o: [UInt8]) -> Bool { - // 10.0.0.0/8 - if o[0] == 10 { + // 0.0.0.0/8 ("this network" / unspecified) + if o[0] == 0 { return true } - // 172.16.0.0/12 - if o[0] == 172, (o[1] & 0xF0) == 16 { + // 10.0.0.0/8 (RFC 1918) + if o[0] == 10 { return true } - // 192.168.0.0/16 - if o[0] == 192, o[1] == 168 { + // 100.64.0.0/10 (RFC 6598 CGNAT / shared address space) + if o[0] == 100, (o[1] & 0xC0) == 64 { return true } - // 169.254.0.0/16 + // 169.254.0.0/16 (link-local / cloud metadata) if o[0] == 169, o[1] == 254 { return true } - // 0.0.0.0 - if o == [0, 0, 0, 0] { + // 172.16.0.0/12 (RFC 1918) + if o[0] == 172, (o[1] & 0xF0) == 16 { + return true + } + // 192.168.0.0/16 (RFC 1918) + if o[0] == 192, o[1] == 168 { + return true + } + // 224.0.0.0/4 (multicast) and 240.0.0.0/4 (reserved / broadcast 255.255.255.255) + if (o[0] & 0xE0) == 224 { return true } return false @@ -266,32 +349,68 @@ private func isBlockedIP(_ ip: IPLiteral) -> Bool { case let .v4(o): return isBlockedV4(o) case let .v6(b): - // Fold IPv4-mapped ::ffff:a.b.c.d back to IPv4. + // ::/128 unspecified + if b.allSatisfy({ $0 == 0 }) { + return true + } + // ::ffff:0:0/96 (IPv4-mapped IPv6, including ::ffff:127.0.0.1 and ::ffff:169.254.169.254) if b[0 ..< 10].allSatisfy({ $0 == 0 }), b[10] == 0xFF, b[11] == 0xFF { - return isBlockedV4(Array(b[12 ..< 16])) + return true } - // :: unspecified - if b.allSatisfy({ $0 == 0 }) { + // ::ffff:0:0:0/96 (IPv4-translated) + if b[0 ..< 8].allSatisfy({ $0 == 0 }), b[8] == 0xFF, b[9] == 0xFF, b[10] == 0, b[11] == 0 { + return true + } + // 64:ff9b::/96 (NAT64 well-known prefix, RFC 6052) and 64:ff9b:1::/48 (RFC 8215) + if b[0] == 0x00, b[1] == 0x64, b[2] == 0xFF, b[3] == 0x9B { + if b[4 ..< 12].allSatisfy({ $0 == 0 }) { + return true + } + if b[4] == 0x00, b[5] == 0x01 { + return true + } + } + // ff00::/8 multicast + if b[0] == 0xFF { return true } let first = (UInt16(b[0]) << 8) | UInt16(b[1]) - return (first & 0xFE00) == 0xFC00 || (first & 0xFFC0) == 0xFE80 // fc00::/7, fe80::/10 + // fc00::/7 ULA, fe80::/10 link-local, fec0::/10 deprecated site-local + return (first & 0xFE00) == 0xFC00 + || (first & 0xFFC0) == 0xFE80 + || (first & 0xFFC0) == 0xFEC0 } } /// Validate a KAS URL for scheme / HTTPS / SSRF constraints. /// /// - `http` is allowed only for loopback hosts (`localhost`, `127.0.0.0/8`, `::1`). -/// - Private, link-local, and unspecified IPs are rejected (IPv4, IPv6 ULA/link-local, -/// and IPv4-mapped IPv6 literals folded back to IPv4). +/// - Rejects URL userinfo, IPv6 zone IDs (`%`), non-canonical IPv4 literals +/// (integer, hex, octal, shorthand), and private, CGNAT, link-local, +/// multicast, reserved, NAT64, IPv4-mapped IPv6, and unspecified addresses. public func validateKasURL(_ urlString: String) throws { guard let url = URL(string: urlString), let scheme = url.scheme?.lowercased() else { throw KASDiscoveryError.invalidURL("Failed to parse URL: \(urlString)") } - let host = url.host ?? "" - guard !host.isEmpty else { + guard url.user == nil, url.password == nil else { + throw KASDiscoveryError.invalidURL("KAS URL must not contain userinfo") + } + let rawHost = url.host ?? "" + guard !rawHost.isEmpty else { throw KASDiscoveryError.invalidURL("KAS URL must have a non-empty host") } + guard !rawHost.contains("%") else { + throw KASDiscoveryError.invalidURL("KAS URL host must not contain IPv6 zone identifiers") + } + let host = stripIPv6Brackets(rawHost) + if isNonCanonicalIPv4Literal(host) { + throw KASDiscoveryError.invalidURL("KAS URL must not use non-canonical IPv4 notation") + } + if let unnormalizedHost = rawAuthorityHost(from: urlString), + unnormalizedHost.contains("%") || isNonCanonicalIPv4Literal(unnormalizedHost) + { + throw KASDiscoveryError.invalidURL("KAS URL must not use non-canonical IPv4 notation or zone identifiers") + } switch scheme { case "https": @@ -305,7 +424,7 @@ public func validateKasURL(_ urlString: String) throws { } if let ip = classifyIP(host), isBlockedIP(ip) { - throw KASDiscoveryError.invalidURL("KAS URL must not target private or link-local IP addresses") + throw KASDiscoveryError.invalidURL("KAS URL must not target private, reserved, or link-local IP addresses") } } @@ -360,6 +479,144 @@ public struct KasEndpoints: Sendable, Equatable { } } +// MARK: - Bounded, No-Redirect HTTP Helper + +enum BoundedHTTPError: Error, Sendable { + case nonHTTPResponse + case responseTooLarge(Int) +} + +/// Executes a URLRequest on `session` while refusing HTTP redirects and enforcing +/// a strict upper bound on buffered response bytes to prevent OOM DoS. +enum BoundedHTTPClient { + static let defaultWellKnownMaxBytes = 1 * 1024 * 1024 // 1 MiB + static let defaultKASMaxBytes = 16 * 1024 * 1024 // 16 MiB + + static func send( + _ request: URLRequest, + on session: URLSession, + maxBytes: Int, + ) async throws -> (Data, HTTPURLResponse) { + let delegate = Delegate(maxBytes: maxBytes) + let task = session.dataTask(with: request) + task.delegate = delegate + + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + delegate.start(task: task, continuation: continuation) + } + } onCancel: { + task.cancel() + } + } + + private final class Delegate: NSObject, URLSessionDataDelegate, @unchecked Sendable { + private let maxBytes: Int + private let lock = NSLock() + private var continuation: CheckedContinuation<(Data, HTTPURLResponse), Error>? + private var httpResponse: HTTPURLResponse? + private var buffer = Data() + private var overflowed = false + private var finished = false + + init(maxBytes: Int) { + self.maxBytes = maxBytes + } + + func start( + task: URLSessionDataTask, + continuation: CheckedContinuation<(Data, HTTPURLResponse), Error>, + ) { + lock.withLock { + self.continuation = continuation + } + task.resume() + } + + private func finish(with result: Result<(Data, HTTPURLResponse), Error>) { + let cont: CheckedContinuation<(Data, HTTPURLResponse), Error>? = lock.withLock { + guard !finished else { return nil } + finished = true + let c = continuation + continuation = nil + return c + } + cont?.resume(with: result) + } + + func urlSession( + _: URLSession, + task _: URLSessionTask, + willPerformHTTPRedirection _: HTTPURLResponse, + newRequest _: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void, + ) { + completionHandler(nil) + } + + func urlSession( + _: URLSession, + dataTask _: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void, + ) { + guard let http = response as? HTTPURLResponse else { + completionHandler(.cancel) + finish(with: .failure(BoundedHTTPError.nonHTTPResponse)) + return + } + if http.expectedContentLength > 0, http.expectedContentLength > Int64(maxBytes) { + lock.withLock { overflowed = true } + completionHandler(.cancel) + finish(with: .failure(BoundedHTTPError.responseTooLarge(maxBytes))) + return + } + lock.withLock { + httpResponse = http + } + completionHandler(.allow) + } + + func urlSession(_: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + let exceeded: Bool = lock.withLock { + if overflowed || finished { + return true + } + if buffer.count > maxBytes - data.count { + overflowed = true + buffer.removeAll(keepingCapacity: false) + return true + } + buffer.append(data) + return false + } + if exceeded { + dataTask.cancel() + finish(with: .failure(BoundedHTTPError.responseTooLarge(maxBytes))) + } + } + + func urlSession(_: URLSession, task _: URLSessionTask, didCompleteWithError error: Error?) { + let (isOverflow, response, data) = lock.withLock { + (overflowed, httpResponse, buffer) + } + if isOverflow { + finish(with: .failure(BoundedHTTPError.responseTooLarge(maxBytes))) + return + } + if let error { + finish(with: .failure(error)) + return + } + guard let response else { + finish(with: .failure(BoundedHTTPError.nonHTTPResponse)) + return + } + finish(with: .success((data, response))) + } + } +} + // MARK: - Well-known discovery /// Fetch the platform's /.well-known/opentdf-configuration document. @@ -370,6 +627,7 @@ public func fetchWellKnown(platformURL: String, { let base = trimmingTrailingSlashes(platformURL) let urlString = "\(base)/.well-known/opentdf-configuration" + try validateKasURL(urlString) guard let url = URL(string: urlString) else { throw KASDiscoveryError.invalidURL("Failed to parse URL: \(urlString)") } @@ -379,13 +637,24 @@ public func fetchWellKnown(platformURL: String, request.timeoutInterval = 30 request.addValue("application/json", forHTTPHeaderField: "Accept") - let (data, response) = try await urlSession.data(for: request) - guard let http = response as? HTTPURLResponse else { - throw KASDiscoveryError.invalidResponse("Non-HTTP response from \(urlString)") + let data: Data + let http: HTTPURLResponse + do { + (data, http) = try await BoundedHTTPClient.send( + request, + on: urlSession, + maxBytes: BoundedHTTPClient.defaultWellKnownMaxBytes, + ) + } catch BoundedHTTPError.nonHTTPResponse { + throw KASDiscoveryError.invalidResponse("Non-HTTP response from \(url.host ?? "platform")") + } catch let BoundedHTTPError.responseTooLarge(limit) { + throw KASDiscoveryError.invalidResponse("Well-known response exceeded \(limit)-byte limit") } + guard (200 ..< 300).contains(http.statusCode) else { - let body = String(data: data, encoding: .utf8) ?? "" - throw KASDiscoveryError.httpError(http.statusCode, "GET \(urlString): \(body)") + let connectCode = String(data: data, encoding: .utf8).flatMap(parseConnectError)?.code + let detail = connectCode.map { "HTTP \(http.statusCode) (\($0))" } ?? "HTTP \(http.statusCode)" + throw KASDiscoveryError.httpError(http.statusCode, detail) } do { diff --git a/OpenTDFKit/KASRewrapClient.swift b/OpenTDFKit/KASRewrapClient.swift index f72f8f0..979d6f8 100644 --- a/OpenTDFKit/KASRewrapClient.swift +++ b/OpenTDFKit/KASRewrapClient.swift @@ -24,21 +24,28 @@ public protocol KASRewrapTransport: Sendable { func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) } -/// The default `KASRewrapTransport`: a `URLSession` task that refuses redirects. +/// The default `KASRewrapTransport`: a `URLSession` task that refuses redirects +/// and bounds response size to prevent unbounded buffering. public struct URLSessionKASTransport: KASRewrapTransport { + public static let defaultMaxResponseBytes = 16 * 1024 * 1024 private let session: URLSession - private let noRedirect = NoRedirectDelegate() + private let maxResponseBytes: Int - public init(session: URLSession = .shared) { + public init(session: URLSession = .shared, maxResponseBytes: Int = URLSessionKASTransport.defaultMaxResponseBytes) { self.session = session + self.maxResponseBytes = maxResponseBytes } public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { - let (data, response) = try await session.data(for: request, delegate: noRedirect) - guard let httpResponse = response as? HTTPURLResponse else { + do { + return try await BoundedHTTPClient.send( + request, + on: session, + maxBytes: maxResponseBytes, + ) + } catch BoundedHTTPError.nonHTTPResponse, BoundedHTTPError.responseTooLarge { throw KASRewrapError.invalidResponse } - return (data, httpResponse) } } @@ -213,8 +220,8 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { let policy: Policy let keyAccessObjects: [KeyAccessObjectWrapper] - init(policy: Policy, keyAccessObjects: [KeyAccessObjectWrapper]) { - algorithm = "ec:secp256r1" + init(policy: Policy, keyAccessObjects: [KeyAccessObjectWrapper], algorithm: String = "ec:secp256r1") { + self.algorithm = algorithm self.policy = policy self.keyAccessObjects = keyAccessObjects } @@ -526,19 +533,29 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { // Build the policy from the parsed header let policyBody: String if let policyBodyData = parsedHeader.policy.body?.body { - // All policy types are base64-encoded for KAS + // All embedded policy types are base64-encoded for KAS policyBody = policyBodyData.base64EncodedString() + } else if parsedHeader.policy.type == .remote, let remote = parsedHeader.policy.remote { + // Encode the remote policy locator instead of a bogus empty JSON object + policyBody = remote.toData().base64EncodedString() } else { - // Send empty JSON object for embedded plaintext policies let emptyJSON = "{}".data(using: .utf8)! policyBody = emptyJSON.base64EncodedString() } let policy = Policy(body: policyBody) + // Match algorithm and signing key to the client's ephemeral key curve + let rewrapAlgorithm: RewrapAlgorithm = switch clientKeyPair.curve { + case .secp256r1: .ecP256 + case .secp384r1: .ecP384 + case .secp521r1: .ecP521 + } + // Build the rewrap request entry let requestEntry = RewrapRequestEntry( policy: policy, keyAccessObjects: [keyAccessWrapper], + algorithm: rewrapAlgorithm.rawValue, ) // Build the unsigned request with clientPublicKey at top level @@ -548,10 +565,15 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { requests: [requestEntry], ) - // Encode to JSON; the KAS expects a signed JWT wrapper around the request body + // Encode to JSON; sign the JWT with the client's ephemeral private key + // corresponding to `clientPublicKey` in the request body let requestBodyJSON = try JSONEncoder().encode(unsignedRequest) let request = try rewrapURLRequest( - body: signedRewrapBody(requestBody: requestBodyJSON, signingKey: signingKey), + body: signedRewrapBody( + requestBody: requestBodyJSON, + privateKeyData: clientKeyPair.privateKey, + curve: clientKeyPair.curve, + ), ) let (data, httpResponse) = try await transport.send(request) @@ -582,13 +604,12 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { throw KASRewrapError.missingWrappedKey } - // Extract session public key from PEM format + // Extract session public key from PEM format matching the client's curve guard let sessionKeyPEM = rewrapResponse.sessionPublicKey else { throw KASRewrapError.missingSessionKey } - // Extract the compressed key from PEM - let sessionKey = try extractCompressedKeyFromPEM(sessionKeyPEM) + let sessionKey = try extractCompressedKeyFromPEM(sessionKeyPEM, expectedAlgorithm: rewrapAlgorithm) return (wrappedKey, sessionKey) default: @@ -631,10 +652,14 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { switch httpResponse.statusCode { case 200: let rewrapResponse = try JSONDecoder().decode(RewrapResponse.self, from: data) + let sentIDs = Set(policyRequest.keyAccessObjects.map(\.keyAccessObjectId)) var wrappedKeys: [String: Data] = [:] for policyEntry in rewrapResponse.responses { for result in policyEntry.results { + guard sentIDs.contains(result.keyAccessObjectId) else { + throw KASRewrapError.invalidResponse + } guard result.status == "permit" else { let reason = result.error ?? result.metadata?["error"]?.stringValue @@ -649,6 +674,9 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { throw KASRewrapError.missingWrappedKey } + guard wrappedKeys[result.keyAccessObjectId] == nil else { + throw KASRewrapError.invalidResponse + } wrappedKeys[result.keyAccessObjectId] = wrappedKeyData } } @@ -782,12 +810,20 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { do { let (sessionPublicKey, _) = try Self.validateEcPublicKeyPEM(sessionPEM) - return try result.wrappedKeys.sorted { $0.key < $1.key }.map { objectID, wrappedKey in - // Request ids are `kao-`. - let index = Int(objectID.dropFirst("kao-".count)) - let sid = index.flatMap { entries.indices.contains($0) ? entries[$0].sid : nil } + // 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-"), + let index = Int(objectID.dropFirst("kao-".count)), + entries.indices.contains(index) + else { + throw KASRewrapError.invalidResponse + } + return (index: index, wrappedKey: wrappedKey) + } + return try indexedResults.sorted { $0.index < $1.index }.map { entry in + let sid = entries[entry.index].sid let key = try Self.unwrapKey( - wrappedKey: wrappedKey, + wrappedKey: entry.wrappedKey, sessionPublicKey: sessionPublicKey, clientPrivateKey: clientPrivateKey.rawRepresentation, salt: Self.standardTDFSessionSalt, @@ -1020,6 +1056,19 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { return try JSONEncoder().encode(SignedRewrapRequest(signed_request_token: signedToken)) } + /// Curve-aware signed Rewrap HTTP body (ES256/ES384/ES512 matching `curve`). + func signedRewrapBody(requestBody: Data, privateKeyData: Data, curve: Curve) throws -> Data { + let now = Int(Date().timeIntervalSince1970) + let signedToken = try createSignedJWT( + requestBody: requestBody, + privateKeyData: privateKeyData, + curve: curve, + issuedAt: now, + expiresAt: now + 60, + ) + return try JSONEncoder().encode(SignedRewrapRequest(signed_request_token: signedToken)) + } + /// A bearer-authenticated POST of `body` to the resolved rewrap endpoint. func rewrapURLRequest(body: Data) throws -> URLRequest { guard let rewrapEndpoint = URL(string: endpoints.rewrapURL) else { @@ -1153,12 +1202,27 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { clientPrivateKey: Data, salt: Data? = nil, ) throws -> SymmetricKey { - try unwrapKey( - wrappedKey: wrappedKey, - sessionPublicKey: P256.KeyAgreement.PublicKey(compressedRepresentation: sessionPublicKey), - clientPrivateKey: P256.KeyAgreement.PrivateKey(rawRepresentation: clientPrivateKey), - salt: salt, - ) + let sharedSecret: SharedSecret + switch (sessionPublicKey.count, clientPrivateKey.count) { + case (33, 32): + let pub = try P256.KeyAgreement.PublicKey(compressedRepresentation: sessionPublicKey) + let priv = try P256.KeyAgreement.PrivateKey(rawRepresentation: clientPrivateKey) + sharedSecret = try priv.sharedSecretFromKeyAgreement(with: pub) + case (49, 48): + let pub = try P384.KeyAgreement.PublicKey(compressedRepresentation: sessionPublicKey) + let priv = try P384.KeyAgreement.PrivateKey(rawRepresentation: clientPrivateKey) + sharedSecret = try priv.sharedSecretFromKeyAgreement(with: pub) + case (67, 66): + let pub = try P521.KeyAgreement.PublicKey(compressedRepresentation: sessionPublicKey) + let priv = try P521.KeyAgreement.PrivateKey(rawRepresentation: clientPrivateKey) + sharedSecret = try priv.sharedSecretFromKeyAgreement(with: pub) + default: + // Fall through to P-256 so invalid key lengths surface CryptoKitError as existing tests expect + let pub = try P256.KeyAgreement.PublicKey(compressedRepresentation: sessionPublicKey) + let priv = try P256.KeyAgreement.PrivateKey(rawRepresentation: clientPrivateKey) + sharedSecret = try priv.sharedSecretFromKeyAgreement(with: pub) + } + return try unwrapKey(wrappedKey: wrappedKey, sharedSecret: sharedSecret, salt: salt) } /// `unwrapKey` with the keys as CryptoKit values, so no caller has to make a @@ -1169,9 +1233,15 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { clientPrivateKey privateKey: P256.KeyAgreement.PrivateKey, salt: Data?, ) throws -> SymmetricKey { - // Perform ECDH with session public key let sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey) + return try unwrapKey(wrappedKey: wrappedKey, sharedSecret: sharedSecret, salt: salt) + } + private static func unwrapKey( + wrappedKey: Data, + sharedSecret: SharedSecret, + salt: Data?, + ) throws -> SymmetricKey { // Derive symmetric key using HKDF // Default to NanoTDF v12 salt (matches KAS rewrap_dek session key derivation) let hkdfSalt = salt ?? CryptoConstants.hkdfSalt @@ -1198,17 +1268,21 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { return SymmetricKey(data: decryptedKey) } - /// Convert a 33-byte compressed P-256 public key to PEM (SubjectPublicKeyInfo) format. - /// - Parameter compressedPublicKey: The 33-byte compressed EC point. - /// - Returns: A PEM-encoded public key string. - /// - Throws: KASRewrapError if the input is not a valid compressed P-256 key. + /// Convert a compressed EC public key (33 bytes P-256, 49 bytes P-384, or 67 bytes P-521) + /// to PEM (SubjectPublicKeyInfo) format. public static func pemRepresentation(compressedPublicKey: Data) throws -> String { - guard compressedPublicKey.count == 33 else { - throw KASRewrapError.invalidEcPublicKey("Expected 33-byte compressed P-256 key, got \(compressedPublicKey.count)") + let derData: Data + switch compressedPublicKey.count { + case 33: + derData = try P256.KeyAgreement.PublicKey(compressedRepresentation: compressedPublicKey).derRepresentation + case 49: + derData = try P384.KeyAgreement.PublicKey(compressedRepresentation: compressedPublicKey).derRepresentation + case 67: + derData = try P521.KeyAgreement.PublicKey(compressedRepresentation: compressedPublicKey).derRepresentation + default: + throw KASRewrapError.invalidEcPublicKey("Expected compressed EC key (33, 49, or 67 bytes), got \(compressedPublicKey.count)") } - let publicKey = try P256.KeyAgreement.PublicKey(compressedRepresentation: compressedPublicKey) - let derData = publicKey.derRepresentation let base64String = derData.base64EncodedString(options: [ .lineLength64Characters, .endLineWithLineFeed, @@ -1221,78 +1295,60 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { """ } - /// Extract compressed P256 public key from PEM format - /// - Parameter pem: PEM-encoded public key (supports various formats) - /// - Returns: Compressed P-256 public key data (33 bytes) - /// - Throws: KASRewrapError.invalidWrappedKeyFormat if PEM parsing fails - private func extractCompressedKeyFromPEM(_ pem: String) throws -> Data { - // Normalize line endings and trim whitespace - let normalizedPEM = pem - .replacingOccurrences(of: "\r\n", with: "\n") - .replacingOccurrences(of: "\r", with: "\n") - .trimmingCharacters(in: .whitespacesAndNewlines) - - // Support multiple PEM header formats - let beginMarkers = [ - "-----BEGIN PUBLIC KEY-----", - "-----BEGIN EC PUBLIC KEY-----", - "-----BEGIN ECDSA PUBLIC KEY-----", - ] - let endMarkers = [ - "-----END PUBLIC KEY-----", - "-----END EC PUBLIC KEY-----", - "-----END ECDSA PUBLIC KEY-----", - ] - - // Extract base64 content by removing all markers - var base64Content = normalizedPEM - for marker in beginMarkers + endMarkers { - base64Content = base64Content.replacingOccurrences(of: marker, with: "") - } - - // Remove all whitespace and newlines - base64Content = base64Content.components(separatedBy: .whitespacesAndNewlines).joined() - - // Validate we have content - guard !base64Content.isEmpty else { - throw KASRewrapError.pemParsingFailed("Empty PEM content") + /// Extract compressed EC public key from PEM format for the expected curve. + private func extractCompressedKeyFromPEM( + _ pem: String, + expectedAlgorithm: RewrapAlgorithm = .ecP256, + ) throws -> Data { + do { + return try Self.validateEcPublicKeyPEM(pem, expectedAlgorithm: expectedAlgorithm).compressedKey + } catch let KASRewrapError.invalidEcPublicKey(reason) { + throw KASRewrapError.pemParsingFailed(reason) } + } - // Decode base64 - guard let keyData = Data(base64Encoded: base64Content) else { - throw KASRewrapError.pemParsingFailed("Invalid base64 encoding") + /// Create a signed JWT using ES256/ES384/ES512 matching `curve`. + func createSignedJWT( + requestBody: Data, + privateKeyData: Data, + curve: Curve, + issuedAt: Int, + expiresAt: Int, + ) throws -> String { + let alg = switch curve { + case .secp256r1: "ES256" + case .secp384r1: "ES384" + case .secp521r1: "ES512" } - // Parse public key - support multiple formats - do { - let publicKey: P256.KeyAgreement.PublicKey - - if keyData.count == 65, keyData[0] == 0x04 { - // Raw uncompressed SEC1 point (0x04 || x || y) - publicKey = try P256.KeyAgreement.PublicKey(x963Representation: keyData) - } else if keyData.count == 33, keyData[0] == 0x02 || keyData[0] == 0x03 { - // Compressed SEC1 point (0x02/0x03 || x) - publicKey = try P256.KeyAgreement.PublicKey(compressedRepresentation: keyData) - } else if keyData.count >= 70 { - // SPKI DER format (91 bytes typical for P-256) - publicKey = try P256.KeyAgreement.PublicKey(derRepresentation: keyData) - } else { - throw KASRewrapError.pemParsingFailed("Unrecognized key format: \(keyData.count) bytes") - } - - let compressedKey = publicKey.compressedRepresentation + let header = ["alg": alg, "typ": "JWT"] + let headerJSON = try JSONSerialization.data(withJSONObject: header) + let headerBase64 = headerJSON.base64URLEncodedString() - // Validate compressed key size - guard compressedKey.count == 33 else { - throw KASRewrapError.pemParsingFailed("Invalid compressed key size: \(compressedKey.count)") - } + 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() - return compressedKey - } catch let error as KASRewrapError { - throw error - } catch { - throw KASRewrapError.pemParsingFailed("Failed to parse key: \(error.localizedDescription)") - } + 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)" } /// Create a signed JWT using ES256 algorithm diff --git a/OpenTDFKit/KASService.swift b/OpenTDFKit/KASService.swift index 0c10957..c066ca3 100644 --- a/OpenTDFKit/KASService.swift +++ b/OpenTDFKit/KASService.swift @@ -153,9 +153,15 @@ public actor KASService { attributes: [String: String]? = nil, ) async throws -> Data { let rewrapEndpoint = baseURL.appendingPathComponent("kas/v2/rewrap") + do { + try validateKasURL(rewrapEndpoint.absoluteString) + } catch { + throw KASServiceError.invalidRequest + } var request = URLRequest(url: rewrapEndpoint) request.httpMethod = "POST" + request.timeoutInterval = 30 request.addValue("application/json", forHTTPHeaderField: "Content-Type") if let credential, let authHeader = credential.authorizationHeader { @@ -173,11 +179,19 @@ public actor KASService { let encoder = JSONEncoder() request.httpBody = try encoder.encode(requestData) - // Perform the network request - let (data, response) = try await urlSession.data(for: request) - - guard let httpResponse = response as? HTTPURLResponse else { + // Perform the network request with no-redirect and bounded response buffering + let data: Data + let httpResponse: HTTPURLResponse + do { + (data, httpResponse) = try await BoundedHTTPClient.send( + request, + on: urlSession, + maxBytes: BoundedHTTPClient.defaultWellKnownMaxBytes, + ) + } catch BoundedHTTPError.nonHTTPResponse { throw KASServiceError.networkError("Invalid response type") + } catch let BoundedHTTPError.responseTooLarge(limit) { + throw KASServiceError.networkError("Response exceeded \(limit)-byte limit") } switch httpResponse.statusCode { @@ -206,11 +220,15 @@ public actor KASService { /// - ephemeralPublicKey: Client's ephemeral public key /// - encryptedKey: The encrypted key to unwrap /// - privateKeyData: The KAS private key to use for decryption + /// - policyBody: Optional serialized policy body to verify against `policyBinding` + /// - policyBinding: Optional GMAC policy binding to verify before rewrapping /// - Returns: Rewrapped key data and the new key pair used for rewrapping func rewrapKeyInternal( ephemeralPublicKey: Data, encryptedKey: Data, privateKeyData: Data, + policyBody: Data? = nil, + policyBinding: Data? = 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 @@ -240,6 +258,21 @@ public actor KASService { 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 { + throw KASServiceError.accessDenied + } + let valid = try await verifyPolicyBinding( + policyBinding: binding, + policyData: body, + symmetricKey: primaryKey, + ) + guard valid else { + throw KASServiceError.accessDenied + } + } + // 3. Generate a new ephemeral key pair for rewrapping let newKeyPair = await keyStore.generateKeyPair() @@ -259,7 +292,8 @@ public actor KASService { tag: tag, ) - let decryptedKey = try AES.GCM.open(sealedBox, using: primaryKey) + var decryptedKey = try AES.GCM.open(sealedBox, using: primaryKey) + defer { decryptedKey.secureZero() } // 5. Create new shared secret for rewrapping let newSharedSecret: SharedSecret @@ -307,32 +341,65 @@ public actor KASService { return (rewrappedKey: result, newKeyPair: newKeyPair) } - /// Process key access request locally (server-side KAS implementation) - /// - Parameters: - /// - ephemeralPublicKey: Client's ephemeral public key - /// - encryptedKey: The encrypted key to unwrap - /// - kasPublicKey: The KAS public key that was used for encryption - /// - Returns: Rewrapped key data + /// Process key access request locally (server-side KAS implementation). + /// When `policyBody` or `policyBinding` is provided, verifies the binding before rewrapping. public func processKeyAccess( ephemeralPublicKey: Data, encryptedKey: Data, kasPublicKey: Data, + policyBody: Data? = nil, + policyBinding: Data? = nil, ) async throws -> Data { // Get the KAS private key corresponding to the KAS public key - guard let privateKeyData = await keyStore.getPrivateKey(forPublicKey: kasPublicKey) else { + guard var privateKeyData = await keyStore.getPrivateKey(forPublicKey: kasPublicKey) else { throw KASServiceError.keyNotFound } + defer { privateKeyData.secureZero() } // Use the internal helper to perform the rewrapping let (rewrappedKey, _) = try await rewrapKeyInternal( ephemeralPublicKey: ephemeralPublicKey, encryptedKey: encryptedKey, privateKeyData: privateKeyData, + policyBody: policyBody, + policyBinding: policyBinding, ) return rewrappedKey } + /// Process a NanoTDF key access request locally, always verifying the header's policy binding. + public func processKeyAccess( + header: Header, + encryptedKey: Data, + kasPublicKey: Data? = nil, + ) async throws -> Data { + let lookupKey = kasPublicKey ?? header.payloadKeyAccess.kasPublicKey + let symmetricKey: SymmetricKey = if !lookupKey.isEmpty { + try await keyStore.derivePayloadSymmetricKey( + kasPublicKey: lookupKey, + tdfEphemeralPublicKey: header.ephemeralPublicKey, + ) + } else { + try await keyStore.derivePayloadSymmetricKey(header: header) + } + do { + try header.verifyPolicyBinding(symmetricKey: symmetricKey) + } catch { + throw KASServiceError.accessDenied + } + guard var privateKeyData = await keyStore.getPrivateKey(forPublicKey: lookupKey) else { + throw KASServiceError.keyNotFound + } + defer { privateKeyData.secureZero() } + let (rewrappedKey, _) = try await rewrapKeyInternal( + ephemeralPublicKey: header.ephemeralPublicKey, + encryptedKey: encryptedKey, + privateKeyData: privateKeyData, + ) + return rewrappedKey + } + /// Verify whether a policy binding is valid /// - Parameters: /// - policyBinding: The policy binding data to verify @@ -374,32 +441,44 @@ public actor KASService { /// - kasPublicKey: The KAS public key /// - Returns: A tuple containing the rewrapped key data and the ID of the key that was used /// - Throws: KAS errors + /// Process a key access request atomically (one-time key) and report a deterministic UUID + /// derived from `kasPublicKey`. public func processKeyAccessWithKeyIdentifier( ephemeralPublicKey: Data, encryptedKey: Data, kasPublicKey: Data, + policyBody: Data? = nil, + policyBinding: Data? = nil, ) async throws -> (rewrappedKey: Data, keyID: UUID) { - // Create a UUID based on the KAS public key bytes - let keyID = UUID() - - // Get the KAS private key corresponding to the KAS public key - guard let privateKeyData = await keyStore.getPrivateKey(forPublicKey: kasPublicKey) else { + // Atomically pop the one-time key so concurrent callers cannot race and reuse it + guard var privateKeyData = await keyStore.popPrivateKey(forPublicKey: kasPublicKey) else { throw KASServiceError.keyNotFound } + defer { privateKeyData.secureZero() } - // Create KeyPairIdentifier for the key - let kasKeyIdentifier = KeyPairIdentifier(publicKey: kasPublicKey) + let keyID = Self.deterministicUUID(for: kasPublicKey) - // Use the internal helper to perform the rewrapping let (rewrappedKey, _) = try await rewrapKeyInternal( ephemeralPublicKey: ephemeralPublicKey, encryptedKey: encryptedKey, privateKeyData: privateKeyData, + policyBody: policyBody, + policyBinding: policyBinding, ) - // Remove the used key from the keystore to ensure one-time use - try await keyStore.removeKeyPair(keyID: kasKeyIdentifier) - return (rewrappedKey: rewrappedKey, keyID: keyID) } + + /// Derives a deterministic RFC 4122 (version 5 / SHA-256 truncated) UUID from the KAS public key bytes. + private static func deterministicUUID(for publicKey: Data) -> UUID { + var digest = Array(SHA256.hash(data: publicKey).prefix(16)) + digest[6] = (digest[6] & 0x0F) | 0x50 // version 5 marker + digest[8] = (digest[8] & 0x3F) | 0x80 // RFC 4122 variant + return UUID(uuid: ( + digest[0], digest[1], digest[2], digest[3], + digest[4], digest[5], digest[6], digest[7], + digest[8], digest[9], digest[10], digest[11], + digest[12], digest[13], digest[14], digest[15], + )) + } } diff --git a/OpenTDFKit/KeyStore.swift b/OpenTDFKit/KeyStore.swift index ff195bf..427fc12 100644 --- a/OpenTDFKit/KeyStore.swift +++ b/OpenTDFKit/KeyStore.swift @@ -1,8 +1,29 @@ import CryptoKit +import Darwin import Foundation // MARK: - Key Types and Storage +/// Reference-counted storage for key pair bytes that zeroes memory on deallocation. +private final class SecureKeyPairStorage: @unchecked Sendable { + var bytes: ContiguousArray + + init(publicKey: Data, privateKey: Data) { + var buffer = ContiguousArray() + buffer.reserveCapacity(publicKey.count + privateKey.count) + publicKey.withUnsafeBytes { buffer.append(contentsOf: $0) } + privateKey.withUnsafeBytes { buffer.append(contentsOf: $0) } + bytes = buffer + } + + deinit { + bytes.withUnsafeMutableBytes { buffer in + guard let baseAddress = buffer.baseAddress else { return } + memset_s(baseAddress, buffer.count, 0, buffer.count) + } + } +} + public struct KeyPairIdentifier: Hashable, Sendable { /// Store the public key bytes directly - already fixed size per curve private let bytes: Data @@ -17,37 +38,25 @@ public struct KeyPairIdentifier: Hashable, Sendable { } public struct StoredKeyPair: Sendable { - // Store all bytes contiguously - private let bytes: ContiguousArray + // Store all bytes contiguously in zero-on-deinit storage + private let storage: SecureKeyPairStorage private let publicKeyLength: Int public var publicKey: Data { - bytes.withUnsafeBufferPointer { buffer in + storage.bytes.withUnsafeBufferPointer { buffer in Data(buffer.prefix(publicKeyLength)) } } var privateKey: Data { - bytes.withUnsafeBufferPointer { buffer in + storage.bytes.withUnsafeBufferPointer { buffer in let privateKeyStart = buffer.index(buffer.startIndex, offsetBy: publicKeyLength) return Data(buffer.suffix(from: privateKeyStart)) } } init(publicKey: Data, privateKey: Data) { - // Single allocation for both keys - var bytes = ContiguousArray() - bytes.reserveCapacity(publicKey.count + privateKey.count) - - // Copy bytes directly without intermediate buffers - publicKey.withUnsafeBytes { pubBytes in - bytes.append(contentsOf: pubBytes) - } - privateKey.withUnsafeBytes { privBytes in - bytes.append(contentsOf: privBytes) - } - - self.bytes = bytes + storage = SecureKeyPairStorage(publicKey: publicKey, privateKey: privateKey) publicKeyLength = publicKey.count } } @@ -81,21 +90,35 @@ public actor KeyStore { totalBytesStored = 0 } + private func recalculateTotalBytesStored() { + totalBytesStored = keyPairs.count * (curve.publicKeyLength + curve.privateKeyLength) + } + public func getPrivateKey(forPublicKey publicKey: Data) -> Data? { let identifier = KeyPairIdentifier(publicKey: publicKey) return keyPairs[identifier]?.privateKey } + /// Atomically retrieves and removes the private key for `publicKey` in a single + /// actor-isolated operation (prevents actor-reentrancy races for one-time keys). + public func popPrivateKey(forPublicKey publicKey: Data) -> Data? { + let identifier = KeyPairIdentifier(publicKey: publicKey) + guard let removed = keyPairs.removeValue(forKey: identifier) else { + return nil + } + recalculateTotalBytesStored() + return removed.privateKey + } + public func store(keyPair: StoredKeyPair) { let identifier = KeyPairIdentifier(publicKey: keyPair.publicKey) keyPairs[identifier] = keyPair - totalBytesStored += curve.publicKeyLength + curve.privateKeyLength + recalculateTotalBytesStored() } /// Batch storage optimized for memory public func storeBatch(pairs: [(publicKey: Data, privateKey: Data)]) { // Pre-allocate for entire batch - let totalNewBytes = pairs.count * (curve.publicKeyLength + curve.privateKeyLength) keyPairs.reserveCapacity(keyPairs.count + pairs.count) // Store all pairs @@ -105,7 +128,7 @@ public actor KeyStore { keyPairs[identifier] = stored } - totalBytesStored += totalNewBytes + recalculateTotalBytesStored() } /// Batch generation method @@ -133,14 +156,13 @@ public actor KeyStore { } // Batch insert all key pairs atomically - let totalBytes = tempPairs.count * (curve.publicKeyLength + curve.privateKeyLength) keyPairs.reserveCapacity(keyPairs.count + tempPairs.count) for (identifier, keyPair) in tempPairs { keyPairs[identifier] = keyPair } - totalBytesStored += totalBytes + recalculateTotalBytesStored() } /// Generates a new key pair using the store's configured curve. @@ -218,37 +240,67 @@ public actor KeyStore { let count = UInt32(countBytes[0]) << 24 | UInt32(countBytes[1]) << 16 | UInt32(countBytes[2]) << 8 | UInt32(countBytes[3]) let pairSize = curve.publicKeyLength + curve.privateKeyLength - let expectedSize = 5 + (Int(count) * pairSize) - guard data.count == expectedSize else { throw KeyStoreError.invalidKeyData } - - // Clear existing data - keyPairs.removeAll(keepingCapacity: true) + guard let countInt = Int(exactly: count) else { throw KeyStoreError.invalidKeyData } + let (pairsBytes, multOverflow) = countInt.multipliedReportingOverflow(by: pairSize) + guard !multOverflow else { throw KeyStoreError.invalidKeyData } + let (expectedSize, addOverflow) = pairsBytes.addingReportingOverflow(5) + guard !addOverflow, data.count == expectedSize else { throw KeyStoreError.invalidKeyData } + var parsedPairs: [KeyPairIdentifier: StoredKeyPair] = Dictionary(minimumCapacity: countInt) var offset = 5 - // Pre-allocate capacity - keyPairs.reserveCapacity(Int(count)) - - // Read fixed-size pairs - for _ in 0 ..< count { + // Read fixed-size pairs into a fresh dictionary before replacing state + for _ in 0 ..< countInt { let pubKeyStart = data.index(data.startIndex, offsetBy: offset) let pubKeyEnd = data.index(pubKeyStart, offsetBy: curve.publicKeyLength) let publicKey = data[pubKeyStart ..< pubKeyEnd] let privKeyStart = pubKeyEnd let privKeyEnd = data.index(privKeyStart, offsetBy: curve.privateKeyLength) - let privateKey = data[privKeyStart ..< privKeyEnd] + var privateKey = Data(data[privKeyStart ..< privKeyEnd]) + defer { privateKey.secureZero() } let keyPair = StoredKeyPair( publicKey: Data(publicKey), - privateKey: Data(privateKey), + privateKey: privateKey, ) let identifier = KeyPairIdentifier(publicKey: keyPair.publicKey) - keyPairs[identifier] = keyPair + parsedPairs[identifier] = keyPair offset += pairSize } + + keyPairs = parsedPairs + recalculateTotalBytesStored() + } + + /// Resolves the private key for a parsed v12 NanoTDF header (whose wire format omits `kasPublicKey`). + /// Matches by optional `ResourceLocator.identifier` (exact public key, public key prefix, or SHA-256 prefix), + /// or falls back to the sole stored key when the store contains exactly one key. + private func resolveV12PrivateKey(identifier: Data?) -> Data? { + if let identifier, !identifier.isEmpty { + var matches: [StoredKeyPair] = [] + for (keyID, pair) in keyPairs { + let pub = keyID.publicKey + if pub == identifier || + (identifier.count <= pub.count && pub.prefix(identifier.count) == identifier) || + Data(SHA256.hash(data: pub)).prefix(identifier.count) == identifier + { + matches.append(pair) + if matches.count > 1 { + return nil + } + } + } + if let unique = matches.first { + return unique.privateKey + } + } + if keyPairs.count == 1, let sole = keyPairs.values.first { + return sole.privateKey + } + return nil } /// Derives the symmetric key for NanoTDF payload decryption using ECDH. @@ -262,7 +314,19 @@ public actor KeyStore { let kasPublicKey = header.payloadKeyAccess.kasPublicKey let tdfEphemeralPublicKey = header.ephemeralPublicKey - return try await derivePayloadSymmetricKey(kasPublicKey: kasPublicKey, tdfEphemeralPublicKey: tdfEphemeralPublicKey) + if !kasPublicKey.isEmpty { + return try await derivePayloadSymmetricKey(kasPublicKey: kasPublicKey, tdfEphemeralPublicKey: tdfEphemeralPublicKey) + } + + // v12 NanoTDF headers omit the KAS public key on the wire; resolve via identifier or sole key. + guard var kasPrivateKeyData = await resolveV12PrivateKey(identifier: header.kas.identifier) else { + throw KeyStoreError.keyNotFound("Private key for v12 NanoTDF header not found in this KeyStore.") + } + defer { kasPrivateKeyData.secureZero() } + return try derivePayloadSymmetricKey( + kasPrivateKeyData: kasPrivateKeyData, + tdfEphemeralPublicKey: tdfEphemeralPublicKey, + ) } /// Derives the symmetric key for NanoTDF payload decryption using ECDH. @@ -282,10 +346,21 @@ public actor KeyStore { // 1. Get the KAS's private key from this KeyStore (the only actor-isolated step; // the ECDH and HKDF below run on the caller's executor so concurrent // decrypts are not serialized through the store). - guard let kasPrivateKeyData = await getPrivateKey(forPublicKey: kasPublicKey) else { + guard var kasPrivateKeyData = await getPrivateKey(forPublicKey: kasPublicKey) else { throw KeyStoreError.keyNotFound("Private key for KAS Public Key \(kasPublicKey.hexString) not found in this KeyStore.") } + defer { kasPrivateKeyData.secureZero() } + return try derivePayloadSymmetricKey( + kasPrivateKeyData: kasPrivateKeyData, + tdfEphemeralPublicKey: tdfEphemeralPublicKey, + ) + } + + private nonisolated func derivePayloadSymmetricKey( + kasPrivateKeyData: Data, + tdfEphemeralPublicKey: Data, + ) throws -> SymmetricKey { // 2. Perform Elliptic Curve Diffie-Hellman (ECDH) Key Agreement let sharedSecret: SharedSecret do { @@ -344,7 +419,7 @@ public actor KeyStore { } // Update storage tracking - totalBytesStored -= (curve.publicKeyLength + curve.privateKeyLength) + recalculateTotalBytesStored() } /// Check if the store contains a key pair matching the given public key diff --git a/OpenTDFKit/NanoTDF.swift b/OpenTDFKit/NanoTDF.swift index e7667f0..a80df85 100644 --- a/OpenTDFKit/NanoTDF.swift +++ b/OpenTDFKit/NanoTDF.swift @@ -23,15 +23,25 @@ public struct NanoTDF: Sendable { public var signature: Signature? /// Decrypts the NanoTDF payload using a KeyStore and returns the plaintext. - /// This is a convenience method that combines key derivation and payload decryption. + /// This is a convenience method that combines key derivation, policy binding verification, and payload decryption. /// - Parameter keyStore: The KeyStore containing the private key corresponding to the KAS public key in the header. /// - Returns: The decrypted plaintext data. - /// - Throws: KeyStoreError, CryptoHelper errors, or other cryptographic errors. + /// - Throws: KeyStoreError, NanoTDFError, CryptoHelper errors, or other cryptographic errors. public func getPlaintext(using keyStore: KeyStore) async throws -> Data { // 1. Derive the symmetric key from the header information let symmetricKey = try await keyStore.derivePayloadSymmetricKey(header: header) - // 2. Use the symmetric key to decrypt the payload + // 2. Verify policy binding and decrypt the payload + return try await getPayloadPlaintext(symmetricKey: symmetricKey) + } + + /// Decrypts the NanoTDF payload using a KeyStore with an explicit KAS public key + /// (useful for v12 headers whose wire format omits the KAS public key when the KeyStore holds multiple keys). + public func getPlaintext(using keyStore: KeyStore, kasPublicKey: Data) async throws -> Data { + let symmetricKey = try await keyStore.derivePayloadSymmetricKey( + kasPublicKey: kasPublicKey, + tdfEphemeralPublicKey: header.ephemeralPublicKey, + ) return try await getPayloadPlaintext(symmetricKey: symmetricKey) } @@ -63,16 +73,19 @@ public struct NanoTDF: Sendable { /// This optimization eliminates actor creation and cross-actor await hops in hot paths. static let sharedCryptoHelper = CryptoHelper() - /// Decrypts the payload ciphertext using the provided symmetric key. + /// Decrypts the payload ciphertext using the provided symmetric key after verifying policy binding. /// Handles nonce padding/adjusting internally. /// - Parameter symmetricKey: The `SymmetricKey` derived during the TDF creation or key access process. /// - Returns: The original plaintext `Data`. - /// - Throws: Errors from `CryptoHelper` or `CryptoKit` if decryption fails (e.g., incorrect key, corrupted data). + /// - Throws: `NanoTDFError.invalidPolicyBinding` if policy binding verification fails, + /// or errors from `CryptoHelper` / `CryptoKit` if decryption fails. public func getPayloadPlaintext(symmetricKey: SymmetricKey) async throws -> Data { + // Verify policy binding before releasing plaintext + try header.verifyPolicyBinding(symmetricKey: symmetricKey) + // Pad the 3-byte NanoTDF IV to the 12 bytes required by AES-GCM let paddedIV = NanoTDF.sharedCryptoHelper.adjustNonce(payload.iv, to: 12) - // Use cipher-aware decryption that routes to CryptoSwift for non-128-bit tags - // (CryptoKit only supports 16-byte tags; NanoTDF default is 8-byte/64-bit) + // Use cipher-aware decryption for all supported GCM tag sizes let cipher = header.payloadSignatureConfig.payloadCipher ?? .aes256GCM64 return try CryptoHelper.decryptNanoTDF( cipher: cipher, @@ -84,13 +97,19 @@ public struct NanoTDF: Sendable { } } -public enum NanoTDFError: Error, CustomStringConvertible { +public enum NanoTDFError: Error, CustomStringConvertible, Equatable { case payloadTooLarge(Int) + case policyTooLarge(Int) + case invalidPolicyBinding public var description: String { switch self { case let .payloadTooLarge(length): "NanoTDF payload length \(length) exceeds the 24-bit limit of 16,777,215 bytes" + case let .policyTooLarge(length): + "NanoTDF embedded policy length \(length) exceeds the 16-bit limit of 65,535 bytes" + case .invalidPolicyBinding: + "NanoTDF policy binding verification failed" } } } @@ -162,7 +181,7 @@ public func createNanoTDF(kas: KasMetadata, policy: inout Policy, plaintext: Dat // Handle error: Embedded policy type must have a body throw PolicyError.missingEmbeddedBody } - policyBody = body.toData() + policyBody = try body.serializedData() case .embeddedEncrypted, .embeddedEncryptedWithPolicyKeyAccess: guard let body = policy.body else { throw PolicyError.missingEmbeddedBody @@ -173,12 +192,6 @@ public func createNanoTDF(kas: KasMetadata, policy: inout Policy, plaintext: Dat throw PolicyError.missingPolicyKeyAccess } - // CRITICAL FIX: For embedded encrypted policies with key access: - // 1. Generate a new ephemeral key pair specifically for policy encryption - // 2. Use the KAS public key (not the ephemeral key from keyAccess) - // 3. Create a new PolicyKeyAccess with our newly generated ephemeral public key - // 4. Encrypt policy with the shared secret derived from our ephemeral private key and KAS public key - // Use the KAS public key for policy encryption (same KAS as for payload) // The keyAccess.ephemeralPublicKey field should NOT be used as the KAS key let policyKasPublicKey = try kas.getPublicKey() @@ -216,51 +229,49 @@ public func createNanoTDF(kas: KasMetadata, policy: inout Policy, plaintext: Dat let policyIV = Data([0, 0, 0]) let adjustedIV = NanoTDF.sharedCryptoHelper.adjustNonce(policyIV, to: 12) - // Encrypt the policy data - let (encryptedPolicyData, _) = try NanoTDF.sharedCryptoHelper.encryptPayload( + // Encrypt the policy data and retain the 16-byte GCM authentication tag (ciphertext || tag) + let (encryptedPolicyData, policyTag) = try NanoTDF.sharedCryptoHelper.encryptPayload( plaintext: body.body, symmetricKey: policySymmetricKey, nonce: adjustedIV, ) + var authenticatedPolicyCiphertext = Data(capacity: encryptedPolicyData.count + policyTag.count) + authenticatedPolicyCiphertext.append(encryptedPolicyData) + authenticatedPolicyCiphertext.append(policyTag) - // Create new encrypted policy body with the encrypted data and updated key access + // Create new encrypted policy body with the authenticated ciphertext and updated key access let encryptedBody = EmbeddedPolicyBody( - body: encryptedPolicyData, + body: authenticatedPolicyCiphertext, keyAccess: updatedPolicyKeyAccess, ) // Update policy with encrypted body policy.body = encryptedBody - policyBody = encryptedBody.toData() + policyBody = try encryptedBody.serializedData() } else if policy.type == .embeddedEncrypted { - // For embedded encrypted policy without PolicyKeyAccess - // The policy should be encrypted with the main TDF symmetric key - - // NanoTDF spec requires IV of 0x000000 for policy encryption - let policyIV = Data([0, 0, 0]) - let adjustedIV = NanoTDF.sharedCryptoHelper.adjustNonce(policyIV, to: 12) - - // Encrypt the policy data using the main TDF symmetric key - let (encryptedPolicyData, _) = try NanoTDF.sharedCryptoHelper.encryptPayload( + // For embedded encrypted policy without PolicyKeyAccess: + // Derive a domain-separated policy encryption key from tdfSymmetricKey so that + // encrypting with IV 0x000000 never reuses the (tdfSymmetricKey, [0; 12]) pair + // used by createGMACBinding, and append the 16-byte GCM authentication tag. + let authenticatedPolicyCiphertext = try CryptoHelper.encryptEmbeddedPolicy( plaintext: body.body, - symmetricKey: tdfSymmetricKey, // Use the main TDF symmetric key - nonce: adjustedIV, + using: tdfSymmetricKey, ) - // Create new encrypted policy body with the encrypted data + // Create new encrypted policy body with the authenticated ciphertext let encryptedBody = EmbeddedPolicyBody( - body: encryptedPolicyData, + body: authenticatedPolicyCiphertext, keyAccess: nil, // No key access for .embeddedEncrypted ) // Update policy with encrypted body policy.body = encryptedBody - policyBody = encryptedBody.toData() + policyBody = try encryptedBody.serializedData() } else { // For plaintext policies, just use the body as is - policyBody = body.toData() + policyBody = try body.serializedData() } } @@ -272,8 +283,9 @@ public func createNanoTDF(kas: KasMetadata, policy: inout Policy, plaintext: Dat // Update the input policy struct with the calculated binding policy.binding = gmacTag - // Step 4: Generate a 3-byte nonce/IV for the payload encryption - let nonce = try NanoTDF.sharedCryptoHelper.generateNonce(length: 3) + // Step 4: Generate a non-zero 3-byte nonce/IV for the payload encryption + // (0x000000 is reserved for GMAC binding / policy encryption and must never be reused) + let nonce = try NanoTDF.sharedCryptoHelper.generateNonZeroNonce(length: 3) // Adjust the 3-byte nonce to 12 bytes for AES-GCM compatibility let nonce12 = NanoTDF.sharedCryptoHelper.adjustNonce(nonce, to: 12) @@ -327,8 +339,11 @@ public func createNanoTDF(kas: KasMetadata, policy: inout Policy, plaintext: Dat /// - config: The `SignatureAndPayloadConfig` indicating the desired signature settings (especially the curve). /// - Throws: `SignatureError.invalidSigning` if signature generation fails, or errors from `CryptoKit`. public func addSignatureToNanoTDF(nanoTDF: inout NanoTDF, privateKey: P256.Signing.PrivateKey, config: SignatureAndPayloadConfig) async throws { + if let requestedCurve = config.signatureCurve, requestedCurve != .secp256r1 { + throw CryptoHelperError.unsupportedCurve + } nanoTDF.header.payloadSignatureConfig.signed = true - nanoTDF.header.payloadSignatureConfig.signatureCurve = config.signatureCurve + nanoTDF.header.payloadSignatureConfig.signatureCurve = .secp256r1 let message = nanoTDF.header.toData() + nanoTDF.payload.toData() let signatureData = try NanoTDF.sharedCryptoHelper.generateECDSASignature( @@ -462,6 +477,69 @@ public struct Header: Sendable { data.append(ephemeralPublicKey) return data } + + /// Verifies the header's policy binding (GMAC or ECDSA) against the serialized policy body. + /// - Parameter symmetricKey: The derived NanoTDF payload symmetric key (used for GMAC binding). + /// - Throws: `NanoTDFError.invalidPolicyBinding` if the binding is missing, malformed, or invalid. + public func verifyPolicyBinding(symmetricKey: SymmetricKey) throws { + guard let binding = policy.binding, !binding.isEmpty else { + throw NanoTDFError.invalidPolicyBinding + } + + let policyBody: Data + switch policy.type { + case .remote: + guard let remote = policy.remote else { + throw NanoTDFError.invalidPolicyBinding + } + policyBody = remote.toData() + case .embeddedPlaintext, .embeddedEncrypted, .embeddedEncryptedWithPolicyKeyAccess: + guard let body = policy.body else { + throw NanoTDFError.invalidPolicyBinding + } + policyBody = try body.serializedData() + } + + if policyBindingConfig.ecdsaBinding { + let valid: Bool + do { + switch policyBindingConfig.curve { + case .secp256r1: + let pub = try P256.Signing.PublicKey(compressedRepresentation: ephemeralPublicKey) + let sig = try P256.Signing.ECDSASignature(rawRepresentation: binding) + valid = pub.isValidSignature(sig, for: policyBody) + case .secp384r1: + let pub = try P384.Signing.PublicKey(compressedRepresentation: ephemeralPublicKey) + let sig = try P384.Signing.ECDSASignature(rawRepresentation: binding) + valid = pub.isValidSignature(sig, for: policyBody) + case .secp521r1: + let pub = try P521.Signing.PublicKey(compressedRepresentation: ephemeralPublicKey) + let sig = try P521.Signing.ECDSASignature(rawRepresentation: binding) + valid = pub.isValidSignature(sig, for: policyBody) + } + } catch { + throw NanoTDFError.invalidPolicyBinding + } + guard valid else { + throw NanoTDFError.invalidPolicyBinding + } + } else { + let nonce = try CryptoKit.AES.GCM.Nonce(data: Data(count: CryptoConstants.aesGcmNonceSize)) + let fullTag = try CryptoKit.AES.GCM.seal( + Data(), + using: symmetricKey, + nonce: nonce, + authenticating: policyBody, + ).tag + guard binding.count == 8 || binding.count == fullTag.count else { + throw NanoTDFError.invalidPolicyBinding + } + let expected = Data(fullTag.prefix(binding.count)) + guard CryptoHelper.constantTimeEquals(binding, expected) else { + throw NanoTDFError.invalidPolicyBinding + } + } + } } /// Represents the encrypted payload section of a NanoTDF object. @@ -483,15 +561,24 @@ public struct Payload: Sendable { self.mac = mac } + /// Serializes the Payload into its binary `Data` representation, validating that `length` + /// fits within the 24-bit wire format limit (`0xFFFFFF`). + public func serializedData() throws -> Data { + try NanoTDF.validatePayloadLength(Int(length)) + return toData() + } + /// Serializes the Payload into its binary `Data` representation according to the NanoTDF specification. - /// Note: Length is serialized as 3 bytes (UInt24). + /// Note: Length is serialized as 3 bytes (UInt24), clamped to `0xFFFFFF` if oversized; use + /// `serializedData()` to throw on overflow. /// - Returns: A `Data` object representing the serialized payload. public func toData() -> Data { + let clampedLength = min(length, 0xFFFFFF) var data = Data() // Serialize length as UInt24 (3 bytes) - data.append(UInt8((length >> 16) & 0xFF)) - data.append(UInt8((length >> 8) & 0xFF)) - data.append(UInt8(length & 0xFF)) + data.append(UInt8((clampedLength >> 16) & 0xFF)) + data.append(UInt8((clampedLength >> 8) & 0xFF)) + data.append(UInt8(clampedLength & 0xFF)) // Append IV, Ciphertext, and MAC tag data.append(iv) data.append(ciphertext) @@ -747,17 +834,27 @@ public struct EmbeddedPolicyBody: Sendable { self.keyAccess = keyAccess } + /// Serializes the EmbeddedPolicyBody, throwing `NanoTDFError.policyTooLarge` if `body.count > 65535`. + public func serializedData() throws -> Data { + guard body.count <= Int(UInt16.max) else { + throw NanoTDFError.policyTooLarge(body.count) + } + return toData() + } + /// Serializes the EmbeddedPolicyBody into its binary `Data` representation. /// Format: Body Length (2 bytes) || Body Data || Optional Key Access Data. + /// Does not trap if `body.count > UInt16.max` (clamps length and bytes consistently); + /// prefer `serializedData()` to enforce the 16-bit limit with an error. /// - Returns: A `Data` object representing the serialized embedded policy body. public func toData() -> Data { var data = Data() - // Serialize body length as UInt16 (2 bytes, big-endian) - let bodyLength = UInt16(body.count) + // Serialize body length as UInt16 (2 bytes, big-endian) without trapping on overflow + let bodyLength = UInt16(clamping: body.count) data.append(UInt8((bodyLength >> 8) & 0xFF)) // High byte data.append(UInt8(bodyLength & 0xFF)) // Low byte - // Append the policy body data - data.append(body) + // Append the policy body data (matching declared length) + data.append(body.prefix(Int(bodyLength))) // Append key access information if present if let keyAccess { data.append(keyAccess.toData()) diff --git a/OpenTDFKit/NanoTDFCollectionBuilder.swift b/OpenTDFKit/NanoTDFCollectionBuilder.swift index 126d7c7..c354fa3 100644 --- a/OpenTDFKit/NanoTDFCollectionBuilder.swift +++ b/OpenTDFKit/NanoTDFCollectionBuilder.swift @@ -150,20 +150,16 @@ public struct NanoTDFCollectionBuilder: Sendable { outputByteCount: 32, ) - // Step 4: Build policy with binding - var policy = try buildPolicy(from: policyConfig) - - // Calculate policy body for binding - let policyBody: Data = switch policyConfig { - case let .remote(locator): - locator.toData() - case let .embeddedPlaintext(data): - data - case let .embeddedEncrypted(data): - data - case let .embeddedEncryptedWithKeyAccess(data, _): - data - } + // Step 4: Build policy (encrypting embedded encrypted policies) and compute binding + // over the serialized policy body (matching createNanoTDF and Header.verifyPolicyBinding). + var (policy, policyBody) = try buildPolicy( + from: policyConfig, + kas: kas, + kasPublicKey: kasPublicKey, + symmetricKey: symmetricKey, + salt: salt, + cryptoHelper: cryptoHelper, + ) // Create GMAC policy binding let binding = try cryptoHelper.createGMACBinding( @@ -203,39 +199,90 @@ public struct NanoTDFCollectionBuilder: Sendable { // MARK: - Private Helpers - private func buildPolicy(from config: CollectionPolicyConfiguration) throws -> Policy { + private func buildPolicy( + from config: CollectionPolicyConfiguration, + kas: KasMetadata, + kasPublicKey: Data, + symmetricKey: SymmetricKey, + salt: Data, + cryptoHelper: CryptoHelper, + ) throws -> (policy: Policy, serializedBody: Data) { switch config { case let .remote(locator): - Policy( + let policy = Policy( type: .remote, body: nil, remote: locator, binding: nil, ) + return (policy, locator.toData()) case let .embeddedPlaintext(data): - Policy( + let body = EmbeddedPolicyBody(body: data, keyAccess: nil) + let serialized = try body.serializedData() + let policy = Policy( type: .embeddedPlaintext, - body: EmbeddedPolicyBody(body: data, keyAccess: nil), + body: body, remote: nil, binding: nil, ) + return (policy, serialized) case let .embeddedEncrypted(data): - Policy( + // Encrypt policy using domain-separated key derived from symmetricKey and append 16-byte GCM tag. + let encryptedData = try CryptoHelper.encryptEmbeddedPolicy( + plaintext: data, + using: symmetricKey, + ) + let body = EmbeddedPolicyBody(body: encryptedData, keyAccess: nil) + let serialized = try body.serializedData() + let policy = Policy( type: .embeddedEncrypted, - body: EmbeddedPolicyBody(body: data, keyAccess: nil), + body: body, remote: nil, binding: nil, ) + return (policy, serialized) case let .embeddedEncryptedWithKeyAccess(data, keyAccess): - Policy( + guard let policyEphemeralKeyPair = cryptoHelper.generateEphemeralKeyPair(curveType: kas.curve) else { + throw NanoTDFCollectionError.keyDerivationFailed("Failed to generate policy ephemeral key pair") + } + guard let policySharedSecret = try cryptoHelper.deriveSharedSecret( + keyPair: policyEphemeralKeyPair, + recipientPublicKey: kasPublicKey, + ) else { + throw NanoTDFCollectionError.keyDerivationFailed("Failed to derive policy shared secret") + } + let policySymmetricKey = cryptoHelper.deriveSymmetricKey( + sharedSecret: policySharedSecret, + salt: salt, + info: Data(), + outputByteCount: 32, + ) + let adjustedIV = cryptoHelper.adjustNonce(Data([0, 0, 0]), to: 12) + let (ciphertext, tag) = try cryptoHelper.encryptPayload( + plaintext: data, + symmetricKey: policySymmetricKey, + nonce: adjustedIV, + ) + var authenticatedCiphertext = Data(capacity: ciphertext.count + tag.count) + authenticatedCiphertext.append(ciphertext) + authenticatedCiphertext.append(tag) + + let updatedKeyAccess = PolicyKeyAccess( + resourceLocator: keyAccess.resourceLocator, + ephemeralPublicKey: policyEphemeralKeyPair.publicKey, + ) + let body = EmbeddedPolicyBody(body: authenticatedCiphertext, keyAccess: updatedKeyAccess) + let serialized = try body.serializedData() + let policy = Policy( type: .embeddedEncryptedWithPolicyKeyAccess, - body: EmbeddedPolicyBody(body: data, keyAccess: keyAccess), + body: body, remote: nil, binding: nil, ) + return (policy, serialized) } } } diff --git a/OpenTDFKit/NanoTDFCollectionDecryptor.swift b/OpenTDFKit/NanoTDFCollectionDecryptor.swift index 6d6467d..46ad64b 100644 --- a/OpenTDFKit/NanoTDFCollectionDecryptor.swift +++ b/OpenTDFKit/NanoTDFCollectionDecryptor.swift @@ -51,33 +51,61 @@ public actor NanoTDFCollectionDecryptor { NanoTDFCollectionDecryptor(symmetricKey: symmetricKey, cipher: cipher) } + /// Creates a decryptor with an already-unwrapped symmetric key after verifying + /// the collection header's policy binding. + public static func withUnwrappedKey( + header: Header, + symmetricKey: SymmetricKey, + ) throws -> NanoTDFCollectionDecryptor { + try header.verifyPolicyBinding(symmetricKey: symmetricKey) + let cipher = header.payloadSignatureConfig.payloadCipher ?? .aes256GCM128 + return NanoTDFCollectionDecryptor(symmetricKey: symmetricKey, cipher: cipher) + } + /// Creates a decryptor using a KeyStore containing the KAS private key. - /// Use this for server-side (KAS) decryption. + /// Verifies the header's policy binding before returning the decryptor. /// /// - Parameters: /// - header: The NanoTDF header from the collection /// - keyStore: The KeyStore containing the KAS private key /// - Returns: A configured decryptor ready for use - /// - Throws: `KeyStoreError` if the private key is not found or key derivation fails + /// - Throws: `KeyStoreError` or `NanoTDFError.invalidPolicyBinding` public static func withKeyStore( header: Header, keyStore: KeyStore, ) async throws -> NanoTDFCollectionDecryptor { // Derive symmetric key using KeyStore's ECDH + HKDF let symmetricKey = try await keyStore.derivePayloadSymmetricKey(header: header) + try header.verifyPolicyBinding(symmetricKey: symmetricKey) + let cipher = header.payloadSignatureConfig.payloadCipher ?? .aes256GCM128 + return NanoTDFCollectionDecryptor(symmetricKey: symmetricKey, cipher: cipher) + } + + /// Creates a decryptor using a KeyStore and an explicit KAS public key + /// (for v12 headers whose wire format omits the KAS public key). + public static func withKeyStore( + header: Header, + keyStore: KeyStore, + kasPublicKey: Data, + ) async throws -> NanoTDFCollectionDecryptor { + let symmetricKey = try await keyStore.derivePayloadSymmetricKey( + kasPublicKey: kasPublicKey, + tdfEphemeralPublicKey: header.ephemeralPublicKey, + ) + try header.verifyPolicyBinding(symmetricKey: symmetricKey) let cipher = header.payloadSignatureConfig.payloadCipher ?? .aes256GCM128 return NanoTDFCollectionDecryptor(symmetricKey: symmetricKey, cipher: cipher) } /// Creates a decryptor using raw key data from a KAS private key. - /// Use this when you have the KAS private key data directly. + /// Verifies the header's policy binding before returning the decryptor. /// /// - Parameters: /// - header: The NanoTDF header from the collection /// - kasPrivateKeyData: The raw private key data /// - curve: The elliptic curve used /// - Returns: A configured decryptor ready for use - /// - Throws: `NanoTDFCollectionError` if key derivation fails + /// - Throws: `NanoTDFCollectionError` or `NanoTDFError.invalidPolicyBinding` public static func withPrivateKey( header: Header, kasPrivateKeyData: Data, @@ -109,6 +137,8 @@ public actor NanoTDFCollectionDecryptor { outputByteCount: 32, ) + try header.verifyPolicyBinding(symmetricKey: symmetricKey) + let cipher = header.payloadSignatureConfig.payloadCipher ?? .aes256GCM128 return NanoTDFCollectionDecryptor(symmetricKey: symmetricKey, cipher: cipher) } diff --git a/OpenTDFKit/NanoTDFCollectionParser.swift b/OpenTDFKit/NanoTDFCollectionParser.swift index 1f012d8..9d556d6 100644 --- a/OpenTDFKit/NanoTDFCollectionParser.swift +++ b/OpenTDFKit/NanoTDFCollectionParser.swift @@ -229,19 +229,23 @@ public enum NanoTDFCollectionFile { throw NanoTDFCollectionError.unexpectedEndOfData } - // Read header length - let headerLength = UInt32(data[0]) << 24 | - UInt32(data[1]) << 16 | - UInt32(data[2]) << 8 | - UInt32(data[3]) - - let headerEnd = 4 + Int(headerLength) - guard data.count >= headerEnd + 4 else { + let base = data.startIndex + + // Read header length (UInt32 big-endian) + let headerLength = UInt64(data[base]) << 24 | + UInt64(data[base + 1]) << 16 | + UInt64(data[base + 2]) << 8 | + UInt64(data[base + 3]) + + guard headerLength <= UInt64(data.count - 8) else { throw NanoTDFCollectionError.unexpectedEndOfData } + let headerStart = base + 4 + let headerEnd = headerStart + Int(headerLength) + // Extract header - let header = data.subdata(in: 4 ..< headerEnd) + let header = Data(data[headerStart ..< headerEnd]) // Read item count let itemCount = UInt32(data[headerEnd]) << 24 | @@ -251,7 +255,7 @@ public enum NanoTDFCollectionFile { // Extract items let itemsStart = headerEnd + 4 - let items = data.subdata(in: itemsStart ..< data.count) + let items = Data(data[itemsStart ..< data.endIndex]) return (header, items, itemCount) } diff --git a/OpenTDFKit/PublicKeyStore.swift b/OpenTDFKit/PublicKeyStore.swift index 040766d..da03327 100644 --- a/OpenTDFKit/PublicKeyStore.swift +++ b/OpenTDFKit/PublicKeyStore.swift @@ -29,6 +29,10 @@ public final class PublicKeyStore: Sendable { func clear() { keys.removeAll() } + + func replaceAll(_ newKeys: [Data]) { + keys = newKeys + } } private let store = InternalStore() @@ -77,18 +81,18 @@ public final class PublicKeyStore: Sendable { let count = UInt32(countBytes[0]) << 24 | UInt32(countBytes[1]) << 16 | UInt32(countBytes[2]) << 8 | UInt32(countBytes[3]) let keySize = curve.publicKeyLength - let expectedSize = 5 + (Int(count) * keySize) - guard data.count == expectedSize else { throw PublicKeyStoreError.invalidData } - - // Clear existing keys - await store.clear() + guard let countInt = Int(exactly: count) else { throw PublicKeyStoreError.invalidData } + let (keysBytes, multOverflow) = countInt.multipliedReportingOverflow(by: keySize) + guard !multOverflow else { throw PublicKeyStoreError.invalidData } + let (expectedSize, addOverflow) = keysBytes.addingReportingOverflow(5) + guard !addOverflow, data.count == expectedSize else { throw PublicKeyStoreError.invalidData } var keys = [Data]() - keys.reserveCapacity(Int(count)) + keys.reserveCapacity(countInt) var offset = 5 - // Read each public key - for _ in 0 ..< count { + // Parse all keys locally before atomically replacing the store + for _ in 0 ..< countInt { let keyStart = data.index(data.startIndex, offsetBy: offset) let keyEnd = data.index(keyStart, offsetBy: keySize) let publicKey = data[keyStart ..< keyEnd] @@ -97,7 +101,7 @@ public final class PublicKeyStore: Sendable { offset += keySize } - await store.addKeys(keys) + await store.replaceAll(keys) } /// Serialize this PublicKeyStore to binary data diff --git a/OpenTDFKit/TDF/StreamingTDFCrypto.swift b/OpenTDFKit/TDF/StreamingTDFCrypto.swift index a2008ed..cec0042 100644 --- a/OpenTDFKit/TDF/StreamingTDFCrypto.swift +++ b/OpenTDFKit/TDF/StreamingTDFCrypto.swift @@ -413,15 +413,31 @@ public enum StreamingTDFCrypto { segments: [EncryptedSegment], symmetricKey: SymmetricKey, chunkSize: Int = defaultChunkSize, + rootSignature: String? = nil, ) 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 } var currentOffset = startOffset + // Buffer decrypted plaintext into a temporary file so no unverified plaintext + // is written to `outputHandle` if a later segment, hash, or root signature fails. + let tempURL = FileManager.default.temporaryDirectory + .appendingPathComponent(".opentdf-stream-decrypt-\(UUID().uuidString).tmp") + FileManager.default.createFile(atPath: tempURL.path, contents: nil) + defer { try? FileManager.default.removeItem(at: tempURL) } + let tempHandle = try FileHandle(forUpdating: tempURL) + defer { try? tempHandle.close() } + + var rawTags: [Data] = [] + rawTags.reserveCapacity(segments.count) + for segment in segments { - guard segment.encryptedSize >= 28 else { + guard segment.encryptedSize >= 28, + let segmentSizeInt = Int(exactly: segment.encryptedSize) + else { throw StreamingCryptoError.malformedSegment(segment.segmentIndex) } let segmentSize = UInt64(segment.encryptedSize) @@ -435,7 +451,7 @@ public enum StreamingTDFCrypto { throw StreamingCryptoError.malformedSegment(segment.segmentIndex) } - let ciphertextSize = Int(segment.encryptedSize) - 28 + let ciphertextSize = segmentSizeInt - 28 var ciphertextAccumulator = Data() ciphertextAccumulator.reserveCapacity(ciphertextSize) var totalRead = 0 @@ -455,34 +471,69 @@ public enum StreamingTDFCrypto { throw StreamingCryptoError.malformedSegment(segment.segmentIndex) } + // Verify segment GMAC hash in constant time + guard let expectedHash = Data(base64Encoded: segment.hash), + CryptoHelper.constantTimeEquals(expectedHash, tagData) + else { + throw StreamingCryptoError.integrityCheckFailed + } + let nonce = try AES.GCM.Nonce(data: ivData) let sealed = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertextAccumulator, tag: tagData) let plaintext = try AES.GCM.open(sealed, using: symmetricKey) - try outputHandle.write(contentsOf: plaintext) + try tempHandle.write(contentsOf: plaintext) + rawTags.append(tagData) currentOffset += segmentSize } guard currentOffset == endOffset else { throw StreamingCryptoError.malformedSegment(segments.last?.segmentIndex ?? 0) } + + if let rootSignature { + let computedRoot = Data(HMAC.authenticationCode( + for: Data(rawTags.joined()), + using: symmetricKey, + )) + guard let expectedRoot = Data(base64Encoded: rootSignature), + CryptoHelper.constantTimeEquals(expectedRoot, computedRoot) + else { + throw StreamingCryptoError.integrityCheckFailed + } + } + + // All segments and integrity checks passed; stream verified plaintext to outputHandle. + try tempHandle.seek(toOffset: 0) + while true { + let chunk = try tempHandle.read(upToCount: chunkSize) ?? Data() + if chunk.isEmpty { + break + } + try outputHandle.write(contentsOf: chunk) + } } public static func decryptPayloadMultiSegmentFromMemory( encryptedPayload: Data, segments: [EncryptedSegment], symmetricKey: SymmetricKey, + rootSignature: String? = nil, ) throws -> Data { + guard !segments.isEmpty else { + throw StreamingCryptoError.malformedSegment(0) + } var plaintext = Data() plaintext.reserveCapacity(encryptedPayload.count) + var rawTags: [Data] = [] + rawTags.reserveCapacity(segments.count) var offset = 0 for segment in segments { - guard segment.encryptedSize >= 28 else { - throw StreamingCryptoError.malformedSegment(segment.segmentIndex) - } - let segmentSize = Int(segment.encryptedSize) - guard offset <= encryptedPayload.count, segmentSize <= encryptedPayload.count - offset else { + guard segment.encryptedSize >= 28, + let segmentSize = Int(exactly: segment.encryptedSize), + offset <= encryptedPayload.count, segmentSize <= encryptedPayload.count - offset + else { throw StreamingCryptoError.malformedSegment(segment.segmentIndex) } @@ -490,19 +541,41 @@ public enum StreamingTDFCrypto { let ivData = encryptedPayload[start ..< start + 12] let ciphertextSize = segmentSize - 28 let ciphertextData = encryptedPayload[start + 12 ..< start + 12 + ciphertextSize] - let tagData = encryptedPayload[start + 12 + ciphertextSize ..< start + segmentSize] + let tagData = Data(encryptedPayload[start + 12 + ciphertextSize ..< start + segmentSize]) + + guard let expectedHash = Data(base64Encoded: segment.hash), + CryptoHelper.constantTimeEquals(expectedHash, tagData) + else { + plaintext.secureZero() + throw StreamingCryptoError.integrityCheckFailed + } let nonce = try AES.GCM.Nonce(data: ivData) let sealed = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertextData, tag: tagData) let segmentPlaintext = try AES.GCM.open(sealed, using: symmetricKey) plaintext.append(segmentPlaintext) + rawTags.append(tagData) offset += segmentSize } guard offset == encryptedPayload.count else { + plaintext.secureZero() throw StreamingCryptoError.malformedSegment(segments.last?.segmentIndex ?? 0) } + + if let rootSignature { + let computedRoot = Data(HMAC.authenticationCode( + for: Data(rawTags.joined()), + using: symmetricKey, + )) + guard let expectedRoot = Data(base64Encoded: rootSignature), + CryptoHelper.constantTimeEquals(expectedRoot, computedRoot) + else { + plaintext.secureZero() + throw StreamingCryptoError.integrityCheckFailed + } + } return plaintext } } @@ -536,6 +609,7 @@ public enum StreamingCryptoError: Error, CustomStringConvertible { case invalidSegmentSize case invalidChunkSize case segmentReadFailed + case integrityCheckFailed public var description: String { switch self { @@ -547,6 +621,8 @@ public enum StreamingCryptoError: Error, CustomStringConvertible { "Chunk size must be positive" case .segmentReadFailed: "Failed to read segment data" + case .integrityCheckFailed: + "Segment or root integrity verification failed" } } } diff --git a/OpenTDFKit/TDF/TDFArchive.swift b/OpenTDFKit/TDF/TDFArchive.swift index 1d5b9b1..d1ba2b6 100644 --- a/OpenTDFKit/TDF/TDFArchive.swift +++ b/OpenTDFKit/TDF/TDFArchive.swift @@ -38,6 +38,11 @@ private final class ManifestCache { public struct TDFArchiveReader { public static let defaultManifestMaxSize = 10 * 1024 * 1024 + /// Default upper bound for in-memory or streamed payload extraction (512 MiB) + /// to prevent unbounded zip-bomb decompression. + public static let defaultPayloadMaxSize = 512 * 1024 * 1024 + /// Maximum initial buffer pre-allocation from untrusted ZIP headers (1 MiB). + private static let maxInitialBufferCapacity = 1 * 1024 * 1024 private let archive: ZIPFoundation.Archive private let cache = ManifestCache() @@ -93,13 +98,17 @@ public struct TDFArchiveReader { let entry = try manifestEntry() try validateEntryPath(entry.path) + guard maxSize >= 0 else { + throw TDFArchiveError.manifestTooLarge + } var total = 0 var result = Data() let _ = try archive.extract(entry) { chunk in - total += chunk.count - if total > maxSize { + let (newTotal, overflow) = total.addingReportingOverflow(chunk.count) + if overflow || newTotal > maxSize { throw TDFArchiveError.manifestTooLarge } + total = newTotal result.append(chunk) } return result @@ -134,35 +143,68 @@ public struct TDFArchiveReader { } public func payloadSize() throws -> Int64 { - try Int64(payloadEntry().uncompressedSize) + let size = try payloadEntry().uncompressedSize + guard let exact = Int64(exactly: size) else { + throw TDFArchiveError.payloadTooLarge + } + return exact } /// Reads the whole payload into memory. - /// - Parameter maxSize: Largest payload accepted, in bytes; `nil` for no cap. + /// - Parameter maxSize: Largest payload accepted, in bytes; defaults to + /// `TDFArchiveReader.defaultPayloadMaxSize` (pass `nil` to opt out of the cap). /// Checked against the ZIP header and again while extracting, since the - /// header's size is not trusted. + /// header's size is not trusted; initial buffer reservation is capped so + /// spoofed ZIP headers cannot trigger OOM. /// - Throws: `TDFArchiveError.payloadTooLarge` when the payload exceeds `maxSize`. - public func payloadData(maxSize: Int? = nil) throws -> Data { + public func payloadData(maxSize: Int? = TDFArchiveReader.defaultPayloadMaxSize) throws -> Data { let entry = try payloadEntry() - let declaredSize = Int(clamping: entry.uncompressedSize) - if let maxSize, declaredSize > maxSize { - throw TDFArchiveError.payloadTooLarge + if let maxSize { + guard maxSize >= 0, entry.uncompressedSize <= UInt64(maxSize) else { + throw TDFArchiveError.payloadTooLarge + } } + let cappedHint = min( + entry.uncompressedSize, + UInt64(maxSize ?? Self.maxInitialBufferCapacity), + UInt64(Self.maxInitialBufferCapacity), + ) var total = 0 - var result = Data(capacity: declaredSize) + var result = Data(capacity: Int(cappedHint)) let _ = try archive.extract(entry) { chunk in - total += chunk.count - if let maxSize, total > maxSize { + let (newTotal, overflow) = total.addingReportingOverflow(chunk.count) + if overflow { + throw TDFArchiveError.payloadTooLarge + } + if let maxSize, newTotal > maxSize { throw TDFArchiveError.payloadTooLarge } + total = newTotal result.append(chunk) } return result } - public func writePayload(to handle: FileHandle) throws { + public func writePayload( + to handle: FileHandle, + maxSize: Int? = TDFArchiveReader.defaultPayloadMaxSize, + ) throws { let entry = try payloadEntry() + if let maxSize { + guard maxSize >= 0, entry.uncompressedSize <= UInt64(maxSize) else { + throw TDFArchiveError.payloadTooLarge + } + } + var total = 0 _ = try archive.extract(entry) { chunk in + let (newTotal, overflow) = total.addingReportingOverflow(chunk.count) + if overflow { + throw TDFArchiveError.payloadTooLarge + } + if let maxSize, newTotal > maxSize { + throw TDFArchiveError.payloadTooLarge + } + total = newTotal try handle.write(contentsOf: chunk) } } diff --git a/OpenTDFKit/TDF/TDFBuilder.swift b/OpenTDFKit/TDF/TDFBuilder.swift index 3a7eb7c..040d105 100644 --- a/OpenTDFKit/TDF/TDFBuilder.swift +++ b/OpenTDFKit/TDF/TDFBuilder.swift @@ -26,14 +26,14 @@ public struct TDFLoader { public func load(from data: Data) throws -> TDFContainer { let reader = try TDFArchiveReader(data: data) let manifest = try reader.manifest() - let payload = try reader.payloadData(maxSize: maxPayloadSize) + let payload = try reader.payloadData(maxSize: maxPayloadSize ?? TDFArchiveReader.defaultPayloadMaxSize) return TDFContainer(manifest: manifest, payload: payload) } public func load(from url: URL) throws -> TDFContainer { let reader = try TDFArchiveReader(url: url) let manifest = try reader.manifest() - let payload = try reader.payloadData(maxSize: maxPayloadSize) + let payload = try reader.payloadData(maxSize: maxPayloadSize ?? TDFArchiveReader.defaultPayloadMaxSize) return TDFContainer(manifest: manifest, payload: payload) } } diff --git a/OpenTDFKit/TDF/TDFCBORContainer.swift b/OpenTDFKit/TDF/TDFCBORContainer.swift index 97220c1..414fb82 100644 --- a/OpenTDFKit/TDF/TDFCBORContainer.swift +++ b/OpenTDFKit/TDF/TDFCBORContainer.swift @@ -281,28 +281,62 @@ public struct TDFCBORDecryptor: Sendable { // Intentionally empty - stateless decryptor } - /// Decrypt a TDF-CBOR container with a symmetric key + /// Decrypt a TDF-CBOR container with a symmetric key, verifying payload encryption flag, + /// algorithm/key size, segment & root integrity, and policy binding. public func decrypt(container: TDFCBORContainer, symmetricKey: SymmetricKey) throws -> Data { - try TDFCrypto.decryptCombinedPayload(container.payloadData, symmetricKey: symmetricKey) + guard container.envelope.payload.isEncrypted else { + throw TDFCBORError.decryptionFailed("Payload is marked as unencrypted") + } + return try TDFDecryptor().decryptEncryptionInfo( + container.encryptionInformation, + payload: container.payloadData, + symmetricKey: symmetricKey, + ) } - /// Decrypt a TDF-CBOR container with a private key (unwraps the symmetric key first) + /// 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") } - guard let ephemeralPublicKey = keyAccess[0].ephemeralPublicKey else { - throw TDFCBORError.decryptionFailed("EC-wrapped key missing ephemeral public key") + 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 symmetricKey = try TDFCrypto.unwrapSymmetricKeyWithEC( - privateKeyPEM: privateKeyPEM, - wrappedKey: keyAccess[0].wrappedKey, - ephemeralPublicKey: ephemeralPublicKey, - ) + let ecObjects = keyAccess.filter { $0.type == .ecWrapped } + guard !ecObjects.isEmpty else { + throw TDFCBORError.decryptionFailed("No ec-wrapped key access object found") + } - return try decrypt(container: container, symmetricKey: symmetricKey) + 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") } } diff --git a/OpenTDFKit/TDF/TDFCBORFormat.swift b/OpenTDFKit/TDF/TDFCBORFormat.swift index 6033b47..bd12e43 100644 --- a/OpenTDFKit/TDF/TDFCBORFormat.swift +++ b/OpenTDFKit/TDF/TDFCBORFormat.swift @@ -109,6 +109,7 @@ public enum TDFCBORKeyAccessKey: Int { case kid = 7 case ephemeralPublicKey = 8 case schemaVersion = 9 + case sid = 10 } /// PolicyBinding integer key mappings @@ -297,10 +298,13 @@ public enum TDFCBORError: Error, CustomStringConvertible, Sendable { // MARK: - TDF-CBOR Extensions public extension TDFCBOREnvelope { - /// Check if data starts with CBOR self-describe tag + /// Check if data starts with CBOR self-describe tag (slice-safe for startIndex > 0) static func hasMagicBytes(_ data: Data) -> Bool { guard data.count >= 3 else { return false } - return data[0] == 0xD9 && data[1] == 0xD9 && data[2] == 0xF7 + let i0 = data.startIndex + let i1 = data.index(after: i0) + let i2 = data.index(after: i1) + return data[i0] == 0xD9 && data[i1] == 0xD9 && data[i2] == 0xF7 } /// Convert to standard TDF manifest format (for KAS integration) @@ -450,19 +454,37 @@ extension TDFCBOREnvelope { .unsignedInt(UInt64(TDFCBORKeyAccessKey.policyBinding.rawValue)): .map(policyBindingMap), ] - // Add optional fields + // Add optional fields without silently dropping values + if let encryptedMetadata = ka.encryptedMetadata { + if let metaData = Data(base64Encoded: encryptedMetadata) { + kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.encryptedMetadata.rawValue))] = .byteString(Array(metaData)) + } else { + kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.encryptedMetadata.rawValue))] = .utf8String(encryptedMetadata) + } + } + if let kid = ka.kid { kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.kid.rawValue))] = .utf8String(kid) } - if let epk = ka.ephemeralPublicKey, let epkData = Data(base64Encoded: epk) { - kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.ephemeralPublicKey.rawValue))] = .byteString(Array(epkData)) + if let epk = ka.ephemeralPublicKey { + if epk.contains("-----BEGIN") { + kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.ephemeralPublicKey.rawValue))] = .utf8String(epk) + } else if let epkData = Data(base64Encoded: epk) { + kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.ephemeralPublicKey.rawValue))] = .byteString(Array(epkData)) + } else { + throw TDFCBORError.cborEncodingFailed("Invalid ephemeralPublicKey encoding") + } } if let sv = ka.schemaVersion { kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.schemaVersion.rawValue))] = .utf8String(sv) } + if let sid = ka.sid { + kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.sid.rawValue))] = .utf8String(sid) + } + return .map(kaMap) } @@ -583,6 +605,194 @@ extension TDFCBOREnvelope { } } + /// Iterative structural pre-validator for raw CBOR bytes. + /// Enforces bounded nesting depth, total item count, and declared byte/element lengths + /// against remaining input bytes BEFORE handing off to SwiftCBOR (which otherwise uses + /// unbounded recursion and allocates declared lengths eagerly in `readN`). + private static func validateCBORStructure( + _ bytes: [UInt8], + maxDepth: Int = 32, + maxItems: Int = 100_000, + ) throws { + enum Frame { + case definite(remaining: Int) + case indefiniteContainer + case indefiniteString(major: UInt8) + } + + var offset = 0 + var itemCount = 0 + var stack: [Frame] = [.definite(remaining: 1)] + + func readArgument(ai: UInt8) throws -> UInt64 { + switch ai { + case 0 ... 23: + return UInt64(ai) + case 24: + guard offset < bytes.count else { + throw TDFCBORError.cborDecodingFailed("Unexpected end of CBOR input") + } + let val = UInt64(bytes[offset]) + offset += 1 + return val + case 25: + guard bytes.count - offset >= 2 else { + throw TDFCBORError.cborDecodingFailed("Unexpected end of CBOR input") + } + let val = (UInt64(bytes[offset]) << 8) | UInt64(bytes[offset + 1]) + offset += 2 + return val + case 26: + guard bytes.count - offset >= 4 else { + throw TDFCBORError.cborDecodingFailed("Unexpected end of CBOR input") + } + let val = (UInt64(bytes[offset]) << 24) + | (UInt64(bytes[offset + 1]) << 16) + | (UInt64(bytes[offset + 2]) << 8) + | UInt64(bytes[offset + 3]) + offset += 4 + return val + case 27: + guard bytes.count - offset >= 8 else { + throw TDFCBORError.cborDecodingFailed("Unexpected end of CBOR input") + } + var val: UInt64 = 0 + for i in 0 ..< 8 { + val = (val << 8) | UInt64(bytes[offset + i]) + } + offset += 8 + return val + default: + throw TDFCBORError.cborDecodingFailed("Invalid CBOR additional info \(ai)") + } + } + + while let frame = stack.popLast() { + guard offset < bytes.count else { + throw TDFCBORError.cborDecodingFailed("Truncated CBOR input") + } + + switch frame { + case let .definite(remaining): + if remaining > 1 { + stack.append(.definite(remaining: remaining - 1)) + } + case .indefiniteContainer: + if bytes[offset] == 0xFF { + offset += 1 + continue + } + stack.append(.indefiniteContainer) + case let .indefiniteString(expectedMajor): + if bytes[offset] == 0xFF { + offset += 1 + continue + } + let initial = bytes[offset] + offset += 1 + let major = initial >> 5 + let ai = initial & 0x1F + guard major == expectedMajor, ai != 31 else { + throw TDFCBORError.cborDecodingFailed("Invalid chunk inside indefinite-length CBOR string") + } + let chunkLen = try readArgument(ai: ai) + guard chunkLen <= UInt64(bytes.count - offset) else { + throw TDFCBORError.cborDecodingFailed("CBOR string chunk length exceeds remaining input") + } + offset += Int(chunkLen) + stack.append(.indefiniteString(major: expectedMajor)) + continue + } + + itemCount += 1 + guard itemCount <= maxItems else { + throw TDFCBORError.cborDecodingFailed("CBOR item count exceeds safety limit") + } + + let initial = bytes[offset] + offset += 1 + let major = initial >> 5 + let ai = initial & 0x1F + + switch major { + case 0, 1: + guard ai != 31 else { + throw TDFCBORError.cborDecodingFailed("Invalid indefinite length for integer") + } + _ = try readArgument(ai: ai) + case 2, 3: + if ai == 31 { + guard stack.count < maxDepth else { + throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") + } + stack.append(.indefiniteString(major: major)) + } else { + let length = try readArgument(ai: ai) + guard length <= UInt64(bytes.count - offset) else { + throw TDFCBORError.cborDecodingFailed("CBOR string length \(length) exceeds remaining input") + } + offset += Int(length) + } + case 4: + if ai == 31 { + guard stack.count < maxDepth else { + throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") + } + stack.append(.indefiniteContainer) + } else { + let count = try readArgument(ai: ai) + guard count <= UInt64(bytes.count - offset) else { + throw TDFCBORError.cborDecodingFailed("CBOR array length \(count) exceeds remaining input") + } + if count > 0 { + guard stack.count < maxDepth else { + throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") + } + stack.append(.definite(remaining: Int(count))) + } + } + case 5: + if ai == 31 { + guard stack.count < maxDepth else { + throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") + } + stack.append(.indefiniteContainer) + } else { + let pairs = try readArgument(ai: ai) + guard pairs <= UInt64((bytes.count - offset) / 2) else { + throw TDFCBORError.cborDecodingFailed("CBOR map length \(pairs) exceeds remaining input") + } + if pairs > 0 { + guard stack.count < maxDepth else { + throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") + } + stack.append(.definite(remaining: Int(pairs) * 2)) + } + } + case 6: + guard ai != 31 else { + throw TDFCBORError.cborDecodingFailed("Invalid indefinite length for CBOR tag") + } + _ = try readArgument(ai: ai) + guard stack.count < maxDepth else { + throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") + } + stack.append(.definite(remaining: 1)) + case 7: + guard ai != 31 else { + throw TDFCBORError.cborDecodingFailed("Unexpected CBOR break byte") + } + _ = try readArgument(ai: ai) + default: + throw TDFCBORError.cborDecodingFailed("Invalid CBOR major type \(major)") + } + } + + guard offset == bytes.count else { + throw TDFCBORError.cborDecodingFailed("Trailing bytes after CBOR root object") + } + } + /// Decode from CBOR bytes public static func fromCBORData(_ data: Data) throws -> TDFCBOREnvelope { // Verify magic bytes @@ -590,8 +800,9 @@ extension TDFCBOREnvelope { throw TDFCBORError.invalidMagicBytes } - // Skip self-describe tag and decode + // Skip self-describe tag, validate CBOR structure iteratively, then decode let cborBytes = Array(data.dropFirst(3)) + try validateCBORStructure(cborBytes) guard let decoded = try? CBOR.decode(cborBytes) else { throw TDFCBORError.cborDecodingFailed("Failed to decode CBOR") } @@ -659,74 +870,78 @@ extension TDFCBOREnvelope { throw TDFCBORError.missingField("payload") } - // Support both integer keys (new spec) and string keys (legacy) - let payloadType: String = { - // Try integer key first (new spec) - if let v = payloadMap[CBOR.unsignedInt(UInt64(TDFCBORPayloadKey.type.rawValue))] { - // Support both integer enum (new) and string (legacy) - switch v { - case let .unsignedInt(i): - return i == TDFCBOREnums.payloadTypeInline ? "inline" : "reference" - case let .utf8String(s): - return s - default: - break - } + // Support both integer keys (new spec) and string keys (legacy), rejecting unknown/mistyped values + let payloadType: String + if let v = payloadMap[CBOR.unsignedInt(UInt64(TDFCBORPayloadKey.type.rawValue))] { + switch v { + case .unsignedInt(TDFCBOREnums.payloadTypeInline): + payloadType = "inline" + case .unsignedInt(TDFCBOREnums.payloadTypeReference): + payloadType = "reference" + case let .utf8String(s): + payloadType = s + default: + throw TDFCBORError.cborDecodingFailed("Invalid payload type value") } - // Fall back to string key (legacy) - if let v = payloadMap["type"], case let .utf8String(s) = v { - return s + } else if let v = payloadMap["type"] { + guard case let .utf8String(s) = v else { + throw TDFCBORError.cborDecodingFailed("Invalid payload type string") } - return "inline" - }() - - let payloadProtocol: String = { - // Try integer key first (new spec) - if let v = payloadMap[CBOR.unsignedInt(UInt64(TDFCBORPayloadKey.protocol.rawValue))] { - // Support both integer enum (new) and string (legacy) - switch v { - case let .unsignedInt(i): - return i == TDFCBOREnums.payloadProtocolBinary ? "binary" : "binary-chunked" - case let .utf8String(s): - return s - default: - break - } + payloadType = s + } else { + throw TDFCBORError.missingField("payload.type") + } + + let payloadProtocol: String + if let v = payloadMap[CBOR.unsignedInt(UInt64(TDFCBORPayloadKey.protocol.rawValue))] { + switch v { + case .unsignedInt(TDFCBOREnums.payloadProtocolBinary): + payloadProtocol = "binary" + case .unsignedInt(TDFCBOREnums.payloadProtocolBinaryChunked): + payloadProtocol = "binary-chunked" + case let .utf8String(s): + payloadProtocol = s + default: + throw TDFCBORError.cborDecodingFailed("Invalid payload protocol value") } - // Fall back to string key (legacy) - if let v = payloadMap["protocol"], case let .utf8String(s) = v { - return s + } else if let v = payloadMap["protocol"] { + guard case let .utf8String(s) = v else { + throw TDFCBORError.cborDecodingFailed("Invalid payload protocol string") } - return "binary" - }() - - let payloadMimeType: String? = { - // Try integer key first (new spec) - if let v = payloadMap[CBOR.unsignedInt(UInt64(TDFCBORPayloadKey.mimeType.rawValue))], - case let .utf8String(s) = v - { - return s + payloadProtocol = s + } else { + throw TDFCBORError.missingField("payload.protocol") + } + + let payloadMimeType: String? + if let v = payloadMap[CBOR.unsignedInt(UInt64(TDFCBORPayloadKey.mimeType.rawValue))] { + guard case let .utf8String(s) = v else { + throw TDFCBORError.cborDecodingFailed("Invalid payload mimeType") } - // Fall back to string key (legacy) - if let v = payloadMap["mimeType"], case let .utf8String(s) = v { - return s + payloadMimeType = s + } else if let v = payloadMap["mimeType"] { + guard case let .utf8String(s) = v else { + throw TDFCBORError.cborDecodingFailed("Invalid payload mimeType") } - return nil - }() - - let payloadIsEncrypted: Bool = { - // Try integer key first (new spec) - if let v = payloadMap[CBOR.unsignedInt(UInt64(TDFCBORPayloadKey.isEncrypted.rawValue))], - case let .boolean(b) = v - { - return b + payloadMimeType = s + } else { + payloadMimeType = nil + } + + let payloadIsEncrypted: Bool + if let v = payloadMap[CBOR.unsignedInt(UInt64(TDFCBORPayloadKey.isEncrypted.rawValue))] { + guard case let .boolean(b) = v else { + throw TDFCBORError.cborDecodingFailed("Invalid payload isEncrypted value") } - // Fall back to string key (legacy) - if let v = payloadMap["isEncrypted"], case let .boolean(b) = v { - return b + payloadIsEncrypted = b + } else if let v = payloadMap["isEncrypted"] { + guard case let .boolean(b) = v else { + throw TDFCBORError.cborDecodingFailed("Invalid payload isEncrypted value") } - return true - }() + payloadIsEncrypted = b + } else { + throw TDFCBORError.missingField("payload.isEncrypted") + } // Try integer key first (new spec), then string key (legacy) let bytes: [UInt8] @@ -742,6 +957,15 @@ extension TDFCBOREnvelope { throw TDFCBORError.binaryPayloadExpected } + // Validate optional payload length if present + if let lenField = payloadMap[CBOR.unsignedInt(UInt64(TDFCBORPayloadKey.length.rawValue))] ?? payloadMap["length"] { + guard case let .unsignedInt(declaredLen) = lenField, + declaredLen == UInt64(bytes.count) + else { + throw TDFCBORError.cborDecodingFailed("Payload length mismatch") + } + } + let payload = TDFBinaryPayload( type: payloadType, protocol: payloadProtocol, @@ -785,24 +1009,33 @@ extension TDFCBOREnvelope { /// Decode encryption information from CBOR private static func decodeEncryptionInfo(_ encMap: [CBOR: CBOR]) throws -> TDFEncryptionInformation { - // Encryption type - var encType: TDFEncryptionInformation.KeyAccessType = .split - if let typeValue = encMap[.unsignedInt(UInt64(TDFCBOREncInfoKey.type.rawValue))], - case let .unsignedInt(typeEnum) = typeValue - { - encType = typeEnum == TDFCBOREnums.encryptionTypeSplit ? .split : .remote + // Encryption type (required, strict enum) + guard let typeValue = encMap[.unsignedInt(UInt64(TDFCBOREncInfoKey.type.rawValue))], + case let .unsignedInt(typeEnum) = typeValue + else { + throw TDFCBORError.missingField("encryptionInformation.type") + } + let encType: TDFEncryptionInformation.KeyAccessType + switch typeEnum { + case TDFCBOREnums.encryptionTypeSplit: encType = .split + case TDFCBOREnums.encryptionTypeRemote: encType = .remote + default: + throw TDFCBORError.cborDecodingFailed("Unsupported encryption type enum: \(typeEnum)") } - // Key access + // Key access (required array of maps) + guard let kaValue = encMap[.unsignedInt(UInt64(TDFCBOREncInfoKey.keyAccess.rawValue))], + case let .array(kaArray) = kaValue + else { + throw TDFCBORError.missingField("keyAccess") + } var keyAccess: [TDFKeyAccessObject] = [] - if let kaValue = encMap[.unsignedInt(UInt64(TDFCBOREncInfoKey.keyAccess.rawValue))], - case let .array(kaArray) = kaValue - { - for kaItem in kaArray { - if case let .map(kaMap) = kaItem { - try keyAccess.append(decodeKeyAccess(kaMap)) - } + keyAccess.reserveCapacity(kaArray.count) + for kaItem in kaArray { + guard case let .map(kaMap) = kaItem else { + throw TDFCBORError.cborDecodingFailed("Expected CBOR map for keyAccess entry") } + try keyAccess.append(decodeKeyAccess(kaMap)) } // Method @@ -821,13 +1054,13 @@ extension TDFCBOREnvelope { } let integrity = try decodeIntegrity(integrityMap) - // Policy - var policy = "" - if let policyValue = encMap[.unsignedInt(UInt64(TDFCBOREncInfoKey.policy.rawValue))], - case let .byteString(policyBytes) = policyValue - { - policy = Data(policyBytes).base64EncodedString() + // Policy (required byteString) + guard let policyValue = encMap[.unsignedInt(UInt64(TDFCBOREncInfoKey.policy.rawValue))], + case let .byteString(policyBytes) = policyValue + else { + throw TDFCBORError.missingField("policy") } + let policy = Data(policyBytes).base64EncodedString() return TDFEncryptionInformation( type: encType, @@ -840,38 +1073,43 @@ extension TDFCBOREnvelope { /// Decode key access from CBOR private static func decodeKeyAccess(_ kaMap: [CBOR: CBOR]) throws -> TDFKeyAccessObject { - // Type - var accessType: TDFKeyAccessObject.AccessType = .wrapped - if let typeValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.type.rawValue))], - case let .unsignedInt(typeEnum) = typeValue - { - accessType = switch typeEnum { - case TDFCBOREnums.keyAccessTypeWrapped: .wrapped - case TDFCBOREnums.keyAccessTypeRemote: .remote - case TDFCBOREnums.keyAccessTypeRemoteWrapped: .remoteWrapped - case TDFCBOREnums.keyAccessTypeEcWrapped: .ecWrapped - default: .wrapped - } + // Type (required, strict enum) + guard let typeValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.type.rawValue))], + case let .unsignedInt(typeEnum) = typeValue + else { + throw TDFCBORError.missingField("keyAccess.type") + } + let accessType: TDFKeyAccessObject.AccessType + switch typeEnum { + case TDFCBOREnums.keyAccessTypeWrapped: accessType = .wrapped + case TDFCBOREnums.keyAccessTypeRemote: accessType = .remote + case TDFCBOREnums.keyAccessTypeRemoteWrapped: accessType = .remoteWrapped + case TDFCBOREnums.keyAccessTypeEcWrapped: accessType = .ecWrapped + default: + throw TDFCBORError.cborDecodingFailed("Unsupported keyAccess type enum: \(typeEnum)") } - // URL - var url = "" - if let urlValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.url.rawValue))], - case let .utf8String(urlStr) = urlValue - { - url = urlStr + // URL (required non-empty string) + guard let urlValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.url.rawValue))], + case let .utf8String(url) = urlValue, !url.isEmpty + else { + throw TDFCBORError.missingField("keyAccess.url") } - // Protocol (currently only "kas" is supported) - let protocolStr = "kas" + // Protocol (required, only kas == 0 is supported) + if let protoValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.protocol.rawValue))] { + guard case .unsignedInt(TDFCBOREnums.keyProtocolKas) = protoValue else { + throw TDFCBORError.cborDecodingFailed("Unsupported keyAccess protocol") + } + } - // Wrapped key - var wrappedKey = "" - if let wkValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.wrappedKey.rawValue))], - case let .byteString(wkBytes) = wkValue - { - wrappedKey = Data(wkBytes).base64EncodedString() + // Wrapped key (required byteString) + guard let wkValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.wrappedKey.rawValue))], + case let .byteString(wkBytes) = wkValue + else { + throw TDFCBORError.missingField("keyAccess.wrappedKey") } + let wrappedKey = Data(wkBytes).base64EncodedString() // Policy binding guard let pbValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.policyBinding.rawValue))], @@ -881,37 +1119,64 @@ extension TDFCBOREnvelope { } let policyBinding = try decodePolicyBinding(pbMap) - // Optional fields + // Optional fields (strict type checks) + var encryptedMetadata: String? + if let metaValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.encryptedMetadata.rawValue))] { + switch metaValue { + case let .byteString(metaBytes): + encryptedMetadata = Data(metaBytes).base64EncodedString() + case let .utf8String(metaStr): + encryptedMetadata = metaStr + default: + throw TDFCBORError.cborDecodingFailed("Invalid keyAccess.encryptedMetadata") + } + } + var kid: String? - if let kidValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.kid.rawValue))], - case let .utf8String(kidStr) = kidValue - { + if let kidValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.kid.rawValue))] { + guard case let .utf8String(kidStr) = kidValue else { + throw TDFCBORError.cborDecodingFailed("Invalid keyAccess.kid") + } kid = kidStr } var ephemeralPublicKey: String? - if let epkValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.ephemeralPublicKey.rawValue))], - case let .byteString(epkBytes) = epkValue - { - ephemeralPublicKey = Data(epkBytes).base64EncodedString() + if let epkValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.ephemeralPublicKey.rawValue))] { + switch epkValue { + case let .byteString(epkBytes): + ephemeralPublicKey = Data(epkBytes).base64EncodedString() + case let .utf8String(epkStr): + ephemeralPublicKey = epkStr + default: + throw TDFCBORError.cborDecodingFailed("Invalid keyAccess.ephemeralPublicKey") + } } var schemaVersion: String? - if let svValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.schemaVersion.rawValue))], - case let .utf8String(svStr) = svValue - { + if let svValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.schemaVersion.rawValue))] { + guard case let .utf8String(svStr) = svValue else { + throw TDFCBORError.cborDecodingFailed("Invalid keyAccess.schemaVersion") + } schemaVersion = svStr } + var sid: String? + if let sidValue = kaMap[.unsignedInt(UInt64(TDFCBORKeyAccessKey.sid.rawValue))] { + guard case let .utf8String(sidStr) = sidValue else { + throw TDFCBORError.cborDecodingFailed("Invalid keyAccess.sid") + } + sid = sidStr + } + return TDFKeyAccessObject( type: accessType, url: url, - protocolValue: TDFKeyAccessObject.AccessProtocol(rawValue: protocolStr) ?? .kas, + protocolValue: .kas, wrappedKey: wrappedKey, policyBinding: policyBinding, - encryptedMetadata: nil, + encryptedMetadata: encryptedMetadata, kid: kid, - sid: nil, + sid: sid, schemaVersion: schemaVersion, ephemeralPublicKey: ephemeralPublicKey, ) @@ -919,50 +1184,54 @@ extension TDFCBOREnvelope { /// Decode policy binding from CBOR private static func decodePolicyBinding(_ pbMap: [CBOR: CBOR]) throws -> TDFPolicyBinding { - var alg = "HS256" - if let algValue = pbMap[.unsignedInt(UInt64(TDFCBORPolicyBindingKey.alg.rawValue))], - case let .unsignedInt(algEnum) = algValue - { + let alg: String + if let algValue = pbMap[.unsignedInt(UInt64(TDFCBORPolicyBindingKey.alg.rawValue))] { + guard case let .unsignedInt(algEnum) = algValue else { + throw TDFCBORError.cborDecodingFailed("Invalid policyBinding.alg") + } alg = try enumToHashAlg(algEnum) + } else { + alg = "HS256" } - var hash = "" - if let hashValue = pbMap[.unsignedInt(UInt64(TDFCBORPolicyBindingKey.hash.rawValue))], - case let .byteString(hashBytes) = hashValue - { - hash = Data(hashBytes).base64EncodedString() + guard let hashValue = pbMap[.unsignedInt(UInt64(TDFCBORPolicyBindingKey.hash.rawValue))], + case let .byteString(hashBytes) = hashValue + else { + throw TDFCBORError.missingField("policyBinding.hash") } + let hash = Data(hashBytes).base64EncodedString() return TDFPolicyBinding(alg: alg, hash: hash) } /// Decode method from CBOR private static func decodeMethod(_ methodMap: [CBOR: CBOR]) throws -> TDFMethodDescriptor { - var algorithm = "AES-256-GCM" - if let algValue = methodMap[.unsignedInt(UInt64(TDFCBORMethodKey.algorithm.rawValue))], - case let .unsignedInt(algEnum) = algValue - { - algorithm = switch algEnum { - case TDFCBOREnums.symmetricAlgAes256Gcm: "AES-256-GCM" - case TDFCBOREnums.symmetricAlgAes128Gcm: "AES-128-GCM" - case TDFCBOREnums.symmetricAlgAes256Cbc: "AES-256-CBC" - case TDFCBOREnums.symmetricAlgAes128Cbc: "AES-128-CBC" - default: - throw TDFCBORError.cborDecodingFailed("Unsupported symmetric algorithm enum: \(algEnum)") - } + guard let algValue = methodMap[.unsignedInt(UInt64(TDFCBORMethodKey.algorithm.rawValue))], + case let .unsignedInt(algEnum) = algValue + else { + throw TDFCBORError.missingField("method.algorithm") + } + let algorithm: String = switch algEnum { + case TDFCBOREnums.symmetricAlgAes256Gcm: "AES-256-GCM" + case TDFCBOREnums.symmetricAlgAes128Gcm: "AES-128-GCM" + case TDFCBOREnums.symmetricAlgAes256Cbc: "AES-256-CBC" + case TDFCBOREnums.symmetricAlgAes128Cbc: "AES-128-CBC" + default: + throw TDFCBORError.cborDecodingFailed("Unsupported symmetric algorithm enum: \(algEnum)") } - var iv = "" - if let ivValue = methodMap[.unsignedInt(UInt64(TDFCBORMethodKey.iv.rawValue))], - case let .byteString(ivBytes) = ivValue - { - iv = Data(ivBytes).base64EncodedString() + guard let ivValue = methodMap[.unsignedInt(UInt64(TDFCBORMethodKey.iv.rawValue))], + case let .byteString(ivBytes) = ivValue + else { + throw TDFCBORError.missingField("method.iv") } + let iv = Data(ivBytes).base64EncodedString() var isStreamable: Bool? = true - if let streamValue = methodMap[.unsignedInt(UInt64(TDFCBORMethodKey.isStreamable.rawValue))], - case let .boolean(streamBool) = streamValue - { + if let streamValue = methodMap[.unsignedInt(UInt64(TDFCBORMethodKey.isStreamable.rawValue))] { + guard case let .boolean(streamBool) = streamValue else { + throw TDFCBORError.cborDecodingFailed("Invalid method.isStreamable") + } isStreamable = streamBool } @@ -980,41 +1249,41 @@ extension TDFCBOREnvelope { let rootSig = try decodeRootSignature(rootSigMap) // Segment hash algorithm - var segmentHashAlg = "GMAC" - if let segAlgValue = intMap[.unsignedInt(UInt64(TDFCBORIntegrityKey.segmentHashAlg.rawValue))], - case let .unsignedInt(segAlgEnum) = segAlgValue - { - segmentHashAlg = try enumToHashAlg(segAlgEnum) + guard let segAlgValue = intMap[.unsignedInt(UInt64(TDFCBORIntegrityKey.segmentHashAlg.rawValue))], + case let .unsignedInt(segAlgEnum) = segAlgValue + else { + throw TDFCBORError.missingField("segmentHashAlg") } + let segmentHashAlg = try enumToHashAlg(segAlgEnum) // Segments + guard let segsValue = intMap[.unsignedInt(UInt64(TDFCBORIntegrityKey.segments.rawValue))], + case let .array(segsArray) = segsValue + else { + throw TDFCBORError.missingField("segments") + } var segments: [TDFSegment] = [] - if let segsValue = intMap[.unsignedInt(UInt64(TDFCBORIntegrityKey.segments.rawValue))], - case let .array(segsArray) = segsValue - { - for segItem in segsArray { - if case let .map(segMap) = segItem { - try segments.append(decodeSegment(segMap)) - } + segments.reserveCapacity(segsArray.count) + for segItem in segsArray { + guard case let .map(segMap) = segItem else { + throw TDFCBORError.cborDecodingFailed("Expected CBOR map for segment") } + try segments.append(decodeSegment(segMap)) } - var segmentSizeDefault: Int64 = 0 - if let ssdValue = intMap[.unsignedInt(UInt64(TDFCBORIntegrityKey.segmentSizeDefault.rawValue))], - case let .unsignedInt(ssd) = ssdValue - { - guard let size = Int64(exactly: ssd) else { - throw TDFCBORError.cborDecodingFailed("Segment size default exceeds Int64") - } - segmentSizeDefault = size + guard let ssdValue = intMap[.unsignedInt(UInt64(TDFCBORIntegrityKey.segmentSizeDefault.rawValue))], + case let .unsignedInt(ssd) = ssdValue, + let segmentSizeDefault = Int64(exactly: ssd) + else { + throw TDFCBORError.cborDecodingFailed("Missing or invalid segmentSizeDefault") } - var encryptedSegmentSizeDefault: Int64 = 0 - if let essdValue = intMap[.unsignedInt(UInt64(TDFCBORIntegrityKey.encryptedSegmentSizeDefault.rawValue))], - case let .unsignedInt(essd) = essdValue - { - guard let size = Int64(exactly: essd) else { - throw TDFCBORError.cborDecodingFailed("Encrypted segment size default exceeds Int64") + var encryptedSegmentSizeDefault: Int64? + if let essdValue = intMap[.unsignedInt(UInt64(TDFCBORIntegrityKey.encryptedSegmentSizeDefault.rawValue))] { + guard case let .unsignedInt(essd) = essdValue, + let size = Int64(exactly: essd) + else { + throw TDFCBORError.cborDecodingFailed("Encrypted segment size default must be a valid Int64") } encryptedSegmentSizeDefault = size } @@ -1030,48 +1299,48 @@ extension TDFCBOREnvelope { /// Decode root signature from CBOR private static func decodeRootSignature(_ sigMap: [CBOR: CBOR]) throws -> TDFRootSignature { - var alg = "HS256" - if let algValue = sigMap[.unsignedInt(UInt64(TDFCBORRootSigKey.alg.rawValue))], - case let .unsignedInt(algEnum) = algValue - { + let alg: String + if let algValue = sigMap[.unsignedInt(UInt64(TDFCBORRootSigKey.alg.rawValue))] { + guard case let .unsignedInt(algEnum) = algValue else { + throw TDFCBORError.cborDecodingFailed("Invalid rootSignature.alg") + } alg = try enumToHashAlg(algEnum) + } else { + alg = "HS256" } - var sig = "" - if let sigValue = sigMap[.unsignedInt(UInt64(TDFCBORRootSigKey.sig.rawValue))], - case let .byteString(sigBytes) = sigValue - { - sig = Data(sigBytes).base64EncodedString() + guard let sigValue = sigMap[.unsignedInt(UInt64(TDFCBORRootSigKey.sig.rawValue))], + case let .byteString(sigBytes) = sigValue + else { + throw TDFCBORError.missingField("rootSignature.sig") } + let sig = Data(sigBytes).base64EncodedString() return TDFRootSignature(alg: alg, sig: sig) } /// Decode segment from CBOR private static func decodeSegment(_ segMap: [CBOR: CBOR]) throws -> TDFSegment { - var hash = "" - if let hashValue = segMap[.unsignedInt(UInt64(TDFCBORSegmentKey.hash.rawValue))], - case let .byteString(hashBytes) = hashValue - { - hash = Data(hashBytes).base64EncodedString() + guard let hashValue = segMap[.unsignedInt(UInt64(TDFCBORSegmentKey.hash.rawValue))], + case let .byteString(hashBytes) = hashValue + else { + throw TDFCBORError.missingField("segment.hash") } + let hash = Data(hashBytes).base64EncodedString() - var segmentSize: Int64 = 0 - if let ssValue = segMap[.unsignedInt(UInt64(TDFCBORSegmentKey.segmentSize.rawValue))], - case let .unsignedInt(ss) = ssValue - { - guard let size = Int64(exactly: ss) else { - throw TDFCBORError.cborDecodingFailed("Segment size exceeds Int64") - } - segmentSize = size + guard let ssValue = segMap[.unsignedInt(UInt64(TDFCBORSegmentKey.segmentSize.rawValue))], + case let .unsignedInt(ss) = ssValue, + let segmentSize = Int64(exactly: ss) + else { + throw TDFCBORError.cborDecodingFailed("Missing or invalid segment.segmentSize") } var encryptedSegmentSize: Int64? - if let essValue = segMap[.unsignedInt(UInt64(TDFCBORSegmentKey.encryptedSegmentSize.rawValue))], - case let .unsignedInt(ess) = essValue - { - guard let size = Int64(exactly: ess) else { - throw TDFCBORError.cborDecodingFailed("Encrypted segment size exceeds Int64") + if let essValue = segMap[.unsignedInt(UInt64(TDFCBORSegmentKey.encryptedSegmentSize.rawValue))] { + guard case let .unsignedInt(ess) = essValue, + let size = Int64(exactly: ess) + else { + throw TDFCBORError.cborDecodingFailed("Encrypted segment size must be a valid Int64") } encryptedSegmentSize = size } diff --git a/OpenTDFKit/TDF/TDFCrypto.swift b/OpenTDFKit/TDF/TDFCrypto.swift index 5aa572a..c963b6c 100644 --- a/OpenTDFKit/TDF/TDFCrypto.swift +++ b/OpenTDFKit/TDF/TDFCrypto.swift @@ -57,7 +57,8 @@ public enum TDFCrypto { /// - Parameter size: Key size (default: .bits256 for AES-256-GCM) /// - Returns: A new symmetric key of the specified size public static func generateSymmetricKey(size: TDFKeySize = .bits256) throws -> SymmetricKey { - let keyData = try randomBytes(count: size.byteCount) + var keyData = try randomBytes(count: size.byteCount) + defer { keyData.secureZero() } return SymmetricKey(data: keyData) } @@ -127,10 +128,16 @@ public enum TDFCrypto { /// - 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 - let keyData = symmetricKey.withUnsafeBytes { Data($0) } + 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 aes = try CryptoSwift.AES( - key: Array(keyData), + key: keyBytes, blockMode: CryptoSwift.CBC(iv: Array(ivData)), padding: .pkcs7, ) @@ -150,10 +157,16 @@ public enum TDFCrypto { throw TDFCryptoError.invalidIVSize(expected: 16, actual: iv.count) } - let keyData = symmetricKey.withUnsafeBytes { Data($0) } + 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 aes = try CryptoSwift.AES( - key: Array(keyData), + key: keyBytes, blockMode: CryptoSwift.CBC(iv: Array(iv)), padding: .pkcs7, ) @@ -174,6 +187,35 @@ public enum TDFCrypto { return TDFPolicyBinding(alg: "HS256", hash: Data(hmac).base64EncodedString()) } + /// Verifies a Standard TDF `policyBinding` against `policyBase64` (the manifest's + /// base64-encoded policy string) and `symmetricKey` (the DEK or KAO key share). + /// Accepts spec-form `Base64(raw HMAC-SHA256)` (32 bytes) and legacy Go SDK + /// `Base64(hex(HMAC-SHA256))` (64 ASCII hex bytes), compared in constant time. + public static func verifyPolicyBinding( + _ binding: TDFPolicyBinding, + policyBase64: String, + symmetricKey: SymmetricKey, + ) -> Bool { + guard binding.alg.isEmpty || binding.alg.uppercased() == "HS256", + !policyBase64.isEmpty, + let decodedHash = Data(base64Encoded: binding.hash) + else { + return false + } + let expectedRaw = Data(HMAC.authenticationCode( + for: Data(policyBase64.utf8), + using: symmetricKey, + )) + if decodedHash.count == expectedRaw.count { + return CryptoHelper.constantTimeEquals(decodedHash, expectedRaw) + } + if decodedHash.count == expectedRaw.count * 2 { + let expectedHex = Data(expectedRaw.hexEncodedString().utf8) + return CryptoHelper.constantTimeEquals(decodedHash, expectedHex) + } + return false + } + public static func data(from symmetricKey: SymmetricKey) -> Data { symmetricKey.withUnsafeBytes { Data($0) } } @@ -229,9 +271,10 @@ public enum TDFCrypto { /// with current KAS unwrap and surfaces as rewrap failures ("access denied" /// / "bad request" after DEK decrypt fails). public static func wrapSymmetricKeyWithRSA(publicKeyPEM: String, symmetricKey: SymmetricKey) throws -> String { - let keyData = symmetricKey.withUnsafeBytes { rawBuffer -> Data in + var keyData = symmetricKey.withUnsafeBytes { rawBuffer -> Data in Data(rawBuffer) } + defer { keyData.secureZero() } let publicKey = try loadRSAPublicKey(fromPEM: publicKeyPEM) var error: Unmanaged? guard let encrypted = SecKeyCreateEncryptedData( @@ -364,83 +407,118 @@ public enum TDFCrypto { } /// Unwrap a symmetric key using EC (ECIES: ECDH + HKDF + AES-GCM), in the - /// TDF-JSON / TDF-CBOR draft scheme (empty HKDF salt); see `wrapSymmetricKeyWithEC`. - /// - Parameters: - /// - privateKeyPEM: The recipient's PEM-encoded EC private key - /// - wrappedKey: The wrapped key data (base64-encoded nonce + ciphertext + tag) - /// - ephemeralPublicKey: The sender's ephemeral public key (PEM or base64 SEC1 compressed) - /// - Returns: The unwrapped symmetric key + /// TDF-JSON / TDF-CBOR draft scheme (empty HKDF salt); supports P-256, P-384, and P-521. public static func unwrapSymmetricKeyWithEC( privateKeyPEM: String, wrappedKey: String, ephemeralPublicKey ephemeralKeyString: String, ) throws -> SymmetricKey { - let privateKey = try P256.KeyAgreement.PrivateKey(pemRepresentation: privateKeyPEM) - return try unwrapSymmetricKeyWithEC( - privateKey: privateKey, - wrappedKey: wrappedKey, - ephemeralPublicKey: ephemeralKeyString, - ) + if let p256Key = try? P256.KeyAgreement.PrivateKey(pemRepresentation: privateKeyPEM) { + return try unwrapSymmetricKeyWithEC( + privateKey: p256Key, + wrappedKey: wrappedKey, + ephemeralPublicKey: ephemeralKeyString, + ) + } + if let p384Key = try? P384.KeyAgreement.PrivateKey(pemRepresentation: privateKeyPEM) { + return try unwrapSymmetricKeyWithEC( + privateKey: p384Key, + wrappedKey: wrappedKey, + ephemeralPublicKey: ephemeralKeyString, + ) + } + if let p521Key = try? P521.KeyAgreement.PrivateKey(pemRepresentation: privateKeyPEM) { + return try unwrapSymmetricKeyWithEC( + privateKey: p521Key, + wrappedKey: wrappedKey, + ephemeralPublicKey: ephemeralKeyString, + ) + } + throw TDFCryptoError.ecKeyAgreementFailed("Unsupported or invalid EC private key PEM") } - /// Unwrap a symmetric key using EC (ECIES: ECDH + HKDF + AES-GCM), in the - /// TDF-JSON / TDF-CBOR draft scheme (empty HKDF salt); see `wrapSymmetricKeyWithEC`. - /// - Parameters: - /// - privateKey: The recipient's private key for ECDH - /// - wrappedKey: The wrapped key data (base64-encoded nonce + ciphertext + tag) - /// - ephemeralPublicKey: The sender's ephemeral public key (PEM or base64 SEC1 compressed) - /// - curve: The EC curve used - /// - Returns: The unwrapped symmetric key + /// Unwrap a symmetric key using P-256 EC (ECIES: ECDH + HKDF + AES-GCM). public static func unwrapSymmetricKeyWithEC( privateKey: P256.KeyAgreement.PrivateKey, wrappedKey: String, ephemeralPublicKey ephemeralKeyString: String, ) throws -> SymmetricKey { - guard let wrappedData = Data(base64Encoded: wrappedKey) else { - throw TDFCryptoError.invalidWrappedKey - } - - // Parse ephemeral public key - supports both PEM and base64 SEC1 (compressed/uncompressed) let ephemeralPublicKey: P256.KeyAgreement.PublicKey if ephemeralKeyString.contains("-----BEGIN") { - // PEM format (legacy) ephemeralPublicKey = try loadECPublicKeyP256(fromPEM: ephemeralKeyString) } else { - // Base64 SEC1 format (compressed or uncompressed) guard let keyData = Data(base64Encoded: ephemeralKeyString) else { throw TDFCryptoError.ecKeyAgreementFailed("Invalid ephemeral key encoding") } - // Try compressed first (33 bytes), then uncompressed (65 bytes) if keyData.count == 33 { ephemeralPublicKey = try P256.KeyAgreement.PublicKey(compressedRepresentation: keyData) } else { ephemeralPublicKey = try P256.KeyAgreement.PublicKey(x963Representation: keyData) } } + let sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: ephemeralPublicKey) + return try unwrapECKey(wrappedKey: wrappedKey, sharedSecret: sharedSecret) + } - // Perform ECDH to get shared secret + /// Unwrap a symmetric key using P-384 EC (ECIES: ECDH + HKDF + AES-GCM). + public static func unwrapSymmetricKeyWithEC( + privateKey: P384.KeyAgreement.PrivateKey, + wrappedKey: String, + ephemeralPublicKey ephemeralKeyString: String, + ) throws -> SymmetricKey { + let ephemeralPublicKey: P384.KeyAgreement.PublicKey + if ephemeralKeyString.contains("-----BEGIN") { + ephemeralPublicKey = try loadECPublicKeyP384(fromPEM: ephemeralKeyString) + } else { + guard let keyData = Data(base64Encoded: ephemeralKeyString) else { + throw TDFCryptoError.ecKeyAgreementFailed("Invalid ephemeral key encoding") + } + if keyData.count == 49 { + ephemeralPublicKey = try P384.KeyAgreement.PublicKey(compressedRepresentation: keyData) + } else { + ephemeralPublicKey = try P384.KeyAgreement.PublicKey(x963Representation: keyData) + } + } let sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: ephemeralPublicKey) + return try unwrapECKey(wrappedKey: wrappedKey, sharedSecret: sharedSecret) + } - // Derive wrapping key using HKDF-SHA256 (empty salt and info for TDF compatibility) + /// Unwrap a symmetric key using P-521 EC (ECIES: ECDH + HKDF + AES-GCM). + public static func unwrapSymmetricKeyWithEC( + privateKey: P521.KeyAgreement.PrivateKey, + wrappedKey: String, + ephemeralPublicKey ephemeralKeyString: String, + ) throws -> SymmetricKey { + let ephemeralPublicKey: P521.KeyAgreement.PublicKey + if ephemeralKeyString.contains("-----BEGIN") { + ephemeralPublicKey = try loadECPublicKeyP521(fromPEM: ephemeralKeyString) + } else { + guard let keyData = Data(base64Encoded: ephemeralKeyString) else { + throw TDFCryptoError.ecKeyAgreementFailed("Invalid ephemeral key encoding") + } + if keyData.count == 67 { + ephemeralPublicKey = try P521.KeyAgreement.PublicKey(compressedRepresentation: keyData) + } else { + ephemeralPublicKey = try P521.KeyAgreement.PublicKey(x963Representation: keyData) + } + } + let sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: ephemeralPublicKey) + return try unwrapECKey(wrappedKey: wrappedKey, sharedSecret: sharedSecret) + } + + private static func unwrapECKey(wrappedKey: String, sharedSecret: SharedSecret) throws -> SymmetricKey { + guard let wrappedData = Data(base64Encoded: wrappedKey), wrappedData.count > 28 else { + throw TDFCryptoError.invalidWrappedKey + } let wrapKey = sharedSecret.hkdfDerivedSymmetricKey( using: SHA256.self, salt: Data(), sharedInfo: Data(), outputByteCount: 32, ) - - // Unwrap using AES-GCM (format: nonce[12] + ciphertext + tag[16]) - guard wrappedData.count > 28 else { - throw TDFCryptoError.invalidWrappedKey - } - let sealedBox = try AES.GCM.SealedBox(combined: wrappedData) var decryptedKey = try AES.GCM.open(sealedBox, using: wrapKey) - - defer { - decryptedKey.secureZero() - } - + defer { decryptedKey.secureZero() } return SymmetricKey(data: decryptedKey) } @@ -509,12 +587,9 @@ public enum TDFCrypto { outputByteCount: 32, ) - // Extract key data - let keyData = symmetricKey.withUnsafeBytes { Data($0) } - - // Wrap using AES-GCM + // 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 AES.GCM.seal(keyData, using: wrapKey, nonce: nonce) + let sealed = try symmetricKey.withUnsafeBytes { try AES.GCM.seal($0, using: wrapKey, nonce: nonce) } // Combined format: nonce + ciphertext + tag let wrappedKey = sealed.combined!.base64EncodedString() @@ -543,10 +618,8 @@ public enum TDFCrypto { outputByteCount: 32, ) - let keyData = symmetricKey.withUnsafeBytes { Data($0) } - let nonce = try AES.GCM.Nonce(data: randomBytes(count: 12)) - let sealed = try AES.GCM.seal(keyData, using: wrapKey, nonce: nonce) + 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) @@ -572,10 +645,8 @@ public enum TDFCrypto { outputByteCount: 32, ) - let keyData = symmetricKey.withUnsafeBytes { Data($0) } - let nonce = try AES.GCM.Nonce(data: randomBytes(count: 12)) - let sealed = try AES.GCM.seal(keyData, using: wrapKey, nonce: nonce) + 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) diff --git a/OpenTDFKit/TDF/TDFFormatDetector.swift b/OpenTDFKit/TDF/TDFFormatDetector.swift index 5211ca4..3e4a4b9 100644 --- a/OpenTDFKit/TDF/TDFFormatDetector.swift +++ b/OpenTDFKit/TDF/TDFFormatDetector.swift @@ -63,7 +63,10 @@ public enum TDFFormatDetector { return nil } - /// Detect the TDF format from a file URL + /// Maximum file size (10 MiB) read into memory for speculative TDF-JSON detection. + public static let maxJSONDetectionSize = 10 * 1024 * 1024 + + /// Detect the TDF format from a file URL without mapping large files into RAM. /// /// - Parameter url: File URL to analyze /// - Returns: Detected format kind, or nil if unknown @@ -90,11 +93,43 @@ public enum TDFFormatDetector { } } - // Fall back to content detection - guard let data = try? Data(contentsOf: url, options: [.mappedIfSafe]) else { + // Fall back to bounded header inspection first (reads at most 4 bytes) + guard let handle = try? FileHandle(forReadingFrom: url) else { + return nil + } + defer { try? handle.close() } + guard let header = try? handle.read(upToCount: 4), !header.isEmpty else { return nil } - return detect(from: data) + + let headerBytes = [UInt8](header) + if headerBytes.count >= 4 { + if Array(headerBytes.prefix(cborMagic.count)) == cborMagic, + headerBytes[cborMagic.count] & 0xE0 == 0xA0 + { + return .cbor + } + if headerBytes == zipMagic { + return .archive + } + } + if headerBytes.count >= 2, Array(headerBytes.prefix(2)) == nanoMagic { + return .nano + } + + // Speculative JSON detection: bound file size before reading & parsing + if headerBytes.first == jsonStart { + guard let size = try? handle.seekToEnd(), + size <= UInt64(maxJSONDetectionSize), + (try? handle.seek(toOffset: 0)) != nil, + let data = try? handle.readToEnd() + else { + return nil + } + return isTDFJSON(data) ? .json : nil + } + + return nil } /// Check if data appears to be TDF-JSON @@ -139,10 +174,11 @@ public extension TDFFormatDetector { static func detectWithDetails(from data: Data) -> TDFFormatDetectionResult? { guard !data.isEmpty else { return nil } - // Check CBOR magic bytes first + // Check CBOR magic bytes first (3-byte self-describe tag + CBOR map major type) if data.count >= 4 { let header = [UInt8](data.prefix(4)) - if header == cborMagic { + let prefix = [UInt8](header.prefix(cborMagic.count)) + if prefix == cborMagic, header[cborMagic.count] & 0xE0 == 0xA0 { return TDFFormatDetectionResult( format: .cbor, confidence: .definitive, diff --git a/OpenTDFKit/TDF/TDFJSONContainer.swift b/OpenTDFKit/TDF/TDFJSONContainer.swift index a6c3a07..ea01d46 100644 --- a/OpenTDFKit/TDF/TDFJSONContainer.swift +++ b/OpenTDFKit/TDF/TDFJSONContainer.swift @@ -288,28 +288,67 @@ public struct TDFJSONDecryptor: Sendable { // Intentionally empty - stateless decryptor } - /// Decrypt a TDF-JSON container with a symmetric key + /// Decrypt a TDF-JSON container with a symmetric key, verifying payload encryption flag, + /// algorithm/key size, segment & root integrity, and policy binding. public func decrypt(container: TDFJSONContainer, symmetricKey: SymmetricKey) throws -> Data { - try TDFCrypto.decryptCombinedPayload(container.payloadData, symmetricKey: symmetricKey) + guard container.envelope.payload.isEncrypted else { + throw TDFJSONError.decryptionFailed("Payload is marked as unencrypted") + } + if let expectedLength = container.envelope.payload.length, + UInt64(container.payloadData.count) != expectedLength + { + throw TDFJSONError.decryptionFailed("Payload length mismatch") + } + return try TDFDecryptor().decryptEncryptionInfo( + container.encryptionInformation, + payload: container.payloadData, + symmetricKey: symmetricKey, + ) } - /// Decrypt a TDF-JSON container with a private key (unwraps the symmetric key first) + /// 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") } - guard let ephemeralPublicKey = keyAccess[0].ephemeralPublicKey else { - throw TDFJSONError.decryptionFailed("EC-wrapped key missing ephemeral public key") + 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 symmetricKey = try TDFCrypto.unwrapSymmetricKeyWithEC( - privateKeyPEM: privateKeyPEM, - wrappedKey: keyAccess[0].wrappedKey, - ephemeralPublicKey: ephemeralPublicKey, - ) + let ecObjects = keyAccess.filter { $0.type == .ecWrapped } + guard !ecObjects.isEmpty else { + throw TDFJSONError.decryptionFailed("No ec-wrapped key access object found") + } - return try decrypt(container: container, symmetricKey: symmetricKey) + 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") } } diff --git a/OpenTDFKit/TDF/TDFJSONFormat.swift b/OpenTDFKit/TDF/TDFJSONFormat.swift index b19cdc7..8282569 100644 --- a/OpenTDFKit/TDF/TDFJSONFormat.swift +++ b/OpenTDFKit/TDF/TDFJSONFormat.swift @@ -162,6 +162,15 @@ public extension TDFJSONEnvelope { guard envelope.tdf == "json" else { throw TDFJSONError.invalidTdfIdentifier(envelope.tdf) } + guard envelope.payload.type == "inline" else { + throw TDFJSONError.payloadDecodeError("Expected payload type 'inline', got '\(envelope.payload.type)'") + } + guard envelope.payload.protocol == "base64" else { + throw TDFJSONError.payloadDecodeError("Expected payload protocol 'base64', got '\(envelope.payload.protocol)'") + } + guard envelope.payload.isEncrypted else { + throw TDFJSONError.payloadDecodeError("Payload must have isEncrypted == true") + } return envelope } @@ -210,11 +219,14 @@ public extension TDFJSONEnvelope { ) } - /// Decode the base64 payload value to raw bytes + /// Decode the base64 payload value to raw bytes, verifying declared length if present func decodePayloadValue() throws -> Data { guard let data = Data(base64Encoded: payload.value) else { throw TDFJSONError.payloadDecodeError("Invalid base64 encoding") } + if let expectedLength = payload.length, UInt64(data.count) != expectedLength { + throw TDFJSONError.payloadDecodeError("Decoded payload length \(data.count) does not match declared length \(expectedLength)") + } return data } } diff --git a/OpenTDFKit/TDF/TDFProcessor.swift b/OpenTDFKit/TDF/TDFProcessor.swift index 82a1e4b..5c9e87a 100644 --- a/OpenTDFKit/TDF/TDFProcessor.swift +++ b/OpenTDFKit/TDF/TDFProcessor.swift @@ -116,6 +116,9 @@ public struct TDFEncryptor { chunkSize: Int = StreamingTDFCrypto.defaultChunkSize, ) throws -> TDFEncryptionResult { try validate(configuration) + guard chunkSize > 0, Int64(chunkSize) <= Int64.max - 28 else { + throw StreamingCryptoError.invalidChunkSize + } let symmetricKey = try TDFCrypto.generateSymmetricKey(size: configuration.keySize) let payloadData: Data let streamingResult: StreamingTDFCrypto.StreamingEncryptionResult @@ -158,7 +161,7 @@ public struct TDFEncryptor { rootSignature: TDFRootSignature(alg: "HS256", sig: rootSignature), segmentHashAlg: "GMAC", segmentSizeDefault: Int64(chunkSize), - encryptedSegmentSizeDefault: Int64(chunkSize + 28), + encryptedSegmentSizeDefault: Int64(chunkSize) + 28, segments: segments, ) @@ -250,11 +253,14 @@ public struct TDFEncryptor { ) let defaultSegmentSize = segmentSizes.first ?? StreamingTDFCrypto.defaultChunkSize + guard defaultSegmentSize > 0, Int64(defaultSegmentSize) <= 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), + encryptedSegmentSizeDefault: Int64(defaultSegmentSize) + 28, segments: segments, ) @@ -337,15 +343,22 @@ public struct TDFEncryptor { segmentSize: Int, ) throws -> TDFEncryptionResult { try validate(configuration) - guard segmentSize > 0 else { + guard segmentSize > 0, Int64(segmentSize) <= Int64.max - 28 else { throw StreamingCryptoError.invalidSegmentSize } let symmetricKey = try TDFCrypto.generateSymmetricKey(size: configuration.keySize) - let segmentCount = max(1, (plaintext.count + segmentSize - 1) / segmentSize) + // Overflow-safe ceiling division for any segmentSize > 0 + let segmentCount = plaintext.isEmpty ? 1 : ((plaintext.count - 1) / segmentSize) + 1 var payloadData = Data() - payloadData.reserveCapacity(plaintext.count + segmentCount * 28) + let (overhead, mulOverflow) = segmentCount.multipliedReportingOverflow(by: 28) + if !mulOverflow { + let (totalCap, addOverflow) = plaintext.count.addingReportingOverflow(overhead) + if !addOverflow { + payloadData.reserveCapacity(totalCap) + } + } var segments: [TDFSegment] = [] segments.reserveCapacity(segmentCount) var tags: [Data] = [] @@ -354,7 +367,8 @@ public struct TDFEncryptor { var offset = plaintext.startIndex repeat { - let end = min(offset + segmentSize, plaintext.endIndex) + let remaining = plaintext.endIndex - offset + let end = offset + min(remaining, segmentSize) let nonce = AES.GCM.Nonce() let sealed = try AES.GCM.seal(plaintext[offset ..< end], using: symmetricKey, nonce: nonce) let segmentStart = payloadData.count @@ -471,11 +485,12 @@ public struct TDFEncryptor { isStreamable: true, ) + let encryptedDefault: Int64? = segmentSizeDefault <= Int64.max - 28 ? segmentSizeDefault + 28 : nil let integrity = TDFIntegrityInformation( rootSignature: TDFRootSignature(alg: "HS256", sig: rootSignature), segmentHashAlg: "GMAC", segmentSizeDefault: segmentSizeDefault, - encryptedSegmentSizeDefault: segmentSizeDefault + 28, + encryptedSegmentSizeDefault: encryptedDefault, segments: segments, ) @@ -548,7 +563,7 @@ public struct TDFDecryptor { let container = try loader.load(from: inputURL) let symmetricKey = try unwrapDEK( - keyAccess: container.manifest.encryptionInformation.keyAccess, + encryptionInformation: container.manifest.encryptionInformation, privateKeyPEM: privateKeyPEM, ) try decrypt(container: container, symmetricKey: symmetricKey).write(to: outputURL) @@ -566,7 +581,7 @@ public struct TDFDecryptor { public func decrypt(container: TDFContainer, privateKeyPEM: String) throws -> Data { let symmetricKey = try unwrapDEK( - keyAccess: container.manifest.encryptionInformation.keyAccess, + encryptionInformation: container.manifest.encryptionInformation, privateKeyPEM: privateKeyPEM, ) return try decrypt(container: container, symmetricKey: symmetricKey) @@ -576,6 +591,14 @@ public struct TDFDecryptor { /// OpenTDFKit (`TDFKeySize.bits128`); other SDKs write AES-256-GCM. static let supportedPayloadAlgorithms: Set = ["AES-256-GCM", "AES-128-GCM"] + static func expectedKeyBitCount(for algorithm: String) throws -> Int { + switch algorithm.uppercased() { + case "AES-256-GCM": 256 + case "AES-128-GCM": 128 + default: throw TDFDecryptError.unsupportedPayloadAlgorithm(algorithm) + } + } + /// Reconstructs a DEK from key access objects per OpenTDF split semantics /// (spec concepts/security.md; Go SDK): objects that share a split ID (`sid`, /// absent treated as "") are alternatives for one share and the first that @@ -588,6 +611,11 @@ public struct TDFDecryptor { /// `TDFDecryptError.keyShareSizeMismatch` / `.missingKeyAccess`. public static func combineKeyShares(_ candidates: [(sid: String?, unwrap: () throws -> Data)]) throws -> Data { var shares: [String: Data] = [:] + defer { + for key in shares.keys { + shares[key]?.secureZero() + } + } var failures: [String: Error] = [:] var splitOrder: [String] = [] for candidate in candidates { @@ -606,13 +634,17 @@ public struct TDFDecryptor { var combined: Data? for sid in splitOrder { guard let share = shares[sid] else { + combined?.secureZero() throw failures[sid] ?? TDFDecryptError.missingKeyAccess } - if let current = combined { + if var current = combined { guard current.count == share.count else { + current.secureZero() throw TDFDecryptError.keyShareSizeMismatch } - combined = Data(zip(current, share).map { $0 ^ $1 }) + let next = Data(zip(current, share).map { $0 ^ $1 }) + current.secureZero() + combined = next } else { combined = share } @@ -623,40 +655,82 @@ public struct TDFDecryptor { return combined } - /// Unwraps every key access object with the RSA private key and combines the - /// shares per split ID (see `combineKeyShares`). - private func unwrapDEK(keyAccess: [TDFKeyAccessObject], privateKeyPEM: String) throws -> SymmetricKey { - let dek = try Self.combineKeyShares(keyAccess.map { kasObject in + /// Unwraps every key access object with the RSA private key, verifies each + /// KAO's `policyBinding` against its unwrapped share, and combines shares per split ID. + private func unwrapDEK( + encryptionInformation: TDFEncryptionInformation, + privateKeyPEM: String, + ) throws -> SymmetricKey { + let policyBase64 = encryptionInformation.policy + var dek = try Self.combineKeyShares(encryptionInformation.keyAccess.map { kasObject in (sid: kasObject.sid, unwrap: { - try TDFCrypto.data(from: TDFCrypto.unwrapSymmetricKeyWithRSA( + let shareKey = try TDFCrypto.unwrapSymmetricKeyWithRSA( privateKeyPEM: privateKeyPEM, wrappedKey: kasObject.wrappedKey, - )) + ) + guard TDFCrypto.verifyPolicyBinding( + kasObject.policyBinding, + policyBase64: policyBase64, + symmetricKey: shareKey, + ) else { + throw TDFDecryptError.policyBindingFailed + } + return TDFCrypto.data(from: shareKey) }) }) + defer { dek.secureZero() } return SymmetricKey(data: dek) } /// Decrypt a Standard TDF payload with its DEK. /// - /// Every segment is opened with AES-GCM, and the manifest's segment hashes and - /// root signature are checked against the payload so dropped, reordered or - /// substituted segments are rejected. - /// - Throws: `TDFDecryptError.missingIntegrityInformation` when the manifest has - /// no segments, `.malformedPayload` when segment sizes do not tile the payload, - /// `.integrityCheckFailed` when a hash or the root signature does not match, - /// or a CryptoKit error when a segment fails authentication. + /// Checks payload algorithm and key size, verifies segment/root integrity and + /// policy binding, and opens every AES-GCM segment. public func decrypt(container: TDFContainer, symmetricKey: SymmetricKey) throws -> Data { - let algorithm = container.manifest.encryptionInformation.method.algorithm - guard Self.supportedPayloadAlgorithms.contains(algorithm.uppercased()) else { - throw TDFDecryptError.unsupportedPayloadAlgorithm(algorithm) + try decryptEncryptionInfo( + container.manifest.encryptionInformation, + payload: container.payload, + symmetricKey: symmetricKey, + ) + } + + /// Shared decryption + integrity + policy-binding verification used by ZIP, JSON, and CBOR decryptors. + func decryptEncryptionInfo( + _ encryptionInformation: TDFEncryptionInformation, + payload: Data, + symmetricKey: SymmetricKey, + ) throws -> Data { + let expectedBits = try Self.expectedKeyBitCount(for: encryptionInformation.method.algorithm) + guard symmetricKey.bitCount == expectedBits else { + throw TDFDecryptError.keySizeMismatch(expected: expectedBits, actual: symmetricKey.bitCount) } - guard let integrity = container.manifest.encryptionInformation.integrityInformation, + guard let integrity = encryptionInformation.integrityInformation, !integrity.segments.isEmpty else { throw TDFDecryptError.missingIntegrityInformation } - return try decryptSegments(payload: container.payload, integrity: integrity, symmetricKey: symmetricKey) + + // Decrypt and verify all segments + root signature before verifying policy binding and returning + var plaintext = try decryptSegments(payload: payload, integrity: integrity, symmetricKey: symmetricKey) + + // Verify policy binding for single-split manifests (in multi-split manifests each KAO binds its own share) + let keyAccess = encryptionInformation.keyAccess + let distinctSplits = Set(keyAccess.map { $0.sid ?? "" }) + if !keyAccess.isEmpty, distinctSplits.count <= 1 { + let bindingValid = keyAccess.contains { kao in + TDFCrypto.verifyPolicyBinding( + kao.policyBinding, + policyBase64: encryptionInformation.policy, + symmetricKey: symmetricKey, + ) + } + guard bindingValid else { + plaintext.secureZero() + throw TDFDecryptError.policyBindingFailed + } + } + + return plaintext } /// Open each `IV || ciphertext || tag` segment laid out back to back in `payload`, @@ -793,6 +867,8 @@ public enum TDFDecryptError: Error, CustomStringConvertible, Equatable { case keyShareSizeMismatch case missingIntegrityInformation case integrityCheckFailed + case policyBindingFailed + case keySizeMismatch(expected: Int, actual: Int) case unsupportedIntegrityAlgorithm(String) case unsupportedPayloadAlgorithm(String) @@ -808,6 +884,10 @@ public enum TDFDecryptError: Error, CustomStringConvertible, Equatable { "Decryption requires integrity information with segment metadata" case .integrityCheckFailed: "Integrity check failed: segment hashes or root signature do not match the payload" + case .policyBindingFailed: + "Policy binding verification failed: manifest policy does not match key access binding" + case let .keySizeMismatch(expected, actual): + "Symmetric key size \(actual) bits does not match manifest algorithm requirement (\(expected) bits)" case let .unsupportedIntegrityAlgorithm(algorithm): "Unsupported integrity algorithm: \(algorithm)" case let .unsupportedPayloadAlgorithm(algorithm): diff --git a/OpenTDFKitTests/KASDiscoveryTests.swift b/OpenTDFKitTests/KASDiscoveryTests.swift index aa1068b..050e9d0 100644 --- a/OpenTDFKitTests/KASDiscoveryTests.swift +++ b/OpenTDFKitTests/KASDiscoveryTests.swift @@ -206,25 +206,44 @@ final class KASDiscoveryTests: XCTestCase { } } - func testWithKasFallbackWhenUriEmpty() throws { - let emptyUri = OpenTDFConfiguration( + func testWithKasFallbackWhenUriEmptyAndNoEndpoints() throws { + let emptyUriNoEndpoints = OpenTDFConfiguration( kas: KasConfig( uri: "", algorithms: [], - publicKeyURL: "https://k.example.com/kas/v2/kas_public_key", - rewrapURL: "https://k.example.com/kas/v2/rewrap", + publicKeyURL: nil, + rewrapURL: nil, connectPublicKeyURL: nil, connectRewrapURL: nil, ), idp: nil, platformIssuer: nil, ) - let filled = emptyUri.withKasFallback(baseURL: "http://localhost:8080") + let filled = emptyUriNoEndpoints.withKasFallback(baseURL: "http://localhost:8080") XCTAssertEqual(filled.kas?.uri, "http://localhost:8080") let ep = try KasEndpoints.from(filled) XCTAssertEqual(ep.transport, .connect) } + func testWithKasFallbackDoesNotOverrideHostileKasBlockWhenUriEmpty() { + let hostileEmptyUri = OpenTDFConfiguration( + kas: KasConfig( + uri: "", + algorithms: [], + publicKeyURL: "https://169.254.169.254/kas/v2/kas_public_key", + rewrapURL: "https://169.254.169.254/kas/v2/rewrap", + connectPublicKeyURL: nil, + connectRewrapURL: nil, + ), + idp: nil, + platformIssuer: nil, + ) + let after = hostileEmptyUri.withKasFallback(baseURL: "http://localhost:8080") + XCTAssertEqual(after.kas?.uri, "") + XCTAssertEqual(after.kas?.rewrapURL, "https://169.254.169.254/kas/v2/rewrap") + XCTAssertThrowsError(try KasEndpoints.from(after)) + } + func testFromConfigThrowsWhenUriEmpty() { let cfg = OpenTDFConfiguration( kas: KasConfig(uri: "", algorithms: [], diff --git a/OpenTDFKitTests/SecurityAuditRegressionTests.swift b/OpenTDFKitTests/SecurityAuditRegressionTests.swift new file mode 100644 index 0000000..52ac589 --- /dev/null +++ b/OpenTDFKitTests/SecurityAuditRegressionTests.swift @@ -0,0 +1,1073 @@ +@preconcurrency import CryptoKit +import Foundation +@testable import OpenTDFKit +import SwiftCBOR +import XCTest +@preconcurrency import ZIPFoundation + +/// Regression test suite for Issue #69 (security & bug audit findings). +final class SecurityAuditRegressionTests: XCTestCase { + override func tearDown() { + MockURLProtocol.handler = nil + super.tearDown() + } + + // MARK: - #1 & #2: Embedded Encrypted Policies (NanoTDF & CollectionBuilder) + + func testEmbeddedEncryptedPolicyRetainsAuthTagAndSeparatesKeyFromGMAC() async throws { + let kasKey = P256.KeyAgreement.PrivateKey() + let kasRL = try XCTUnwrap(ResourceLocator(protocolEnum: .https, body: "kas.example.com")) + let kasMetadata = try KasMetadata(resourceLocator: kasRL, publicKey: kasKey.publicKey, curve: .secp256r1) + + let policyPlaintext = Data(#"{"uuid":"p1","body":{"dataAttributes":[],"dissem":[]}}"#.utf8) + var policy = Policy( + type: .embeddedEncrypted, + body: EmbeddedPolicyBody(body: policyPlaintext), + remote: nil, + binding: nil, + ) + + let nano = try await createNanoTDF( + kas: kasMetadata, + policy: &policy, + plaintext: Data("secret payload".utf8), + ) + + let encryptedPolicyBody = try XCTUnwrap(nano.header.policy.body?.body) + // Must NOT be cleartext and MUST include 16-byte GCM tag + XCTAssertNotEqual(encryptedPolicyBody, policyPlaintext) + XCTAssertEqual(encryptedPolicyBody.count, policyPlaintext.count + 16) + + // Derive payload symmetric key as KAS would + let sharedSecret = try kasKey.sharedSecretFromKeyAgreement( + with: P256.KeyAgreement.PublicKey(compressedRepresentation: nano.header.ephemeralPublicKey), + ) + let symmetricKey = sharedSecret.hkdfDerivedSymmetricKey( + using: SHA256.self, + salt: CryptoHelper.computeHKDFSalt(version: Header.versionV12), + sharedInfo: Data(), + outputByteCount: 32, + ) + + // Policy binding must verify + XCTAssertNoThrow(try nano.header.verifyPolicyBinding(symmetricKey: symmetricKey)) + + // Embedded encrypted policy decrypts cleanly with domain-separated key + let recoveredPolicy = try CryptoHelper.decryptEmbeddedPolicy( + ciphertextWithTag: encryptedPolicyBody, + using: symmetricKey, + ) + XCTAssertEqual(recoveredPolicy, policyPlaintext) + + // Tampering with ciphertext or tag must fail authentication + var tampered = encryptedPolicyBody + tampered[tampered.count - 1] ^= 0x01 + XCTAssertThrowsError(try CryptoHelper.decryptEmbeddedPolicy( + ciphertextWithTag: tampered, + using: symmetricKey, + )) + + // Domain-separated policy key must NOT equal the raw payload symmetricKey + let policyKey = CryptoHelper.deriveEmbeddedPolicyKey(from: symmetricKey) + XCTAssertNotEqual( + policyKey.withUnsafeBytes { Data($0) }, + symmetricKey.withUnsafeBytes { Data($0) }, + ) + } + + func testEmbeddedEncryptedWithPolicyKeyAccessRetainsAuthTag() async throws { + let kasKey = P256.KeyAgreement.PrivateKey() + let kasRL = try XCTUnwrap(ResourceLocator(protocolEnum: .https, body: "kas.example.com")) + let kasMetadata = try KasMetadata(resourceLocator: kasRL, publicKey: kasKey.publicKey, curve: .secp256r1) + + let policyPlaintext = Data(#"{"classification":"top-secret"}"#.utf8) + let placeholderKey = P256.KeyAgreement.PrivateKey().publicKey.compressedRepresentation + var policy = Policy( + type: .embeddedEncryptedWithPolicyKeyAccess, + body: EmbeddedPolicyBody( + body: policyPlaintext, + keyAccess: PolicyKeyAccess(resourceLocator: kasRL, ephemeralPublicKey: placeholderKey), + ), + remote: nil, + binding: nil, + ) + + let nano = try await createNanoTDF(kas: kasMetadata, policy: &policy, plaintext: Data("msg".utf8)) + let encryptedBody = try XCTUnwrap(nano.header.policy.body) + XCTAssertEqual(encryptedBody.body.count, policyPlaintext.count + 16) + + let policyKeyAccess = try XCTUnwrap(encryptedBody.keyAccess) + let shared = try kasKey.sharedSecretFromKeyAgreement( + with: P256.KeyAgreement.PublicKey(compressedRepresentation: policyKeyAccess.ephemeralPublicKey), + ) + let policyKey = shared.hkdfDerivedSymmetricKey( + using: SHA256.self, + salt: CryptoHelper.computeHKDFSalt(version: Header.versionV12), + sharedInfo: Data(), + outputByteCount: 32, + ) + let nonce = try AES.GCM.Nonce(data: Data(count: 12)) + let ct = encryptedBody.body.dropLast(16) + let tag = encryptedBody.body.suffix(16) + let opened = try AES.GCM.open(AES.GCM.SealedBox(nonce: nonce, ciphertext: ct, tag: tag), using: policyKey) + XCTAssertEqual(opened, policyPlaintext) + } + + func testNanoTDFCollectionBuilderEncryptsEmbeddedEncryptedPolicyAndComputesValidBinding() async throws { + let keyStore = KeyStore(curve: .secp256r1) + let kasService = KASService(keyStore: keyStore, baseURL: URL(string: "https://kas.example.com")!) + let kasMetadata = try await kasService.generateKasMetadata() + + let policyPlaintext = Data(#"{"attr":"confidential"}"#.utf8) + let collection = try await NanoTDFCollectionBuilder() + .kasMetadata(kasMetadata) + .policy(.embeddedEncrypted(policyPlaintext)) + .build() + + let header = await collection.header + let symKey = await collection.getSymmetricKey() + let storedBody = try XCTUnwrap(header.policy.body?.body) + + // Must NOT be cleartext + XCTAssertNotEqual(storedBody, policyPlaintext) + XCTAssertEqual(storedBody.count, policyPlaintext.count + 16) + XCTAssertEqual( + try CryptoHelper.decryptEmbeddedPolicy(ciphertextWithTag: storedBody, using: symKey), + policyPlaintext, + ) + + // Decryptor with KeyStore must verify the GMAC binding over EmbeddedPolicyBody.toData() + let item = try await collection.encryptItem(plaintext: Data("hello".utf8)) + let decryptor = try await NanoTDFCollectionDecryptor.withKeyStore(header: header, keyStore: keyStore) + let decrypted = try await decryptor.decryptItem(item) + XCTAssertEqual(decrypted, Data("hello".utf8)) + } + + // MARK: - #4: Data Slices (startIndex > 0) & Offset Safety + + func testBinaryParserAndCollectionFileHandleNonZeroStartIndexSlices() async throws { + let keyStore = KeyStore(curve: .secp256r1) + let kasService = KASService(keyStore: keyStore, baseURL: URL(string: "https://kas.example.com")!) + let kasMetadata = try await kasService.generateKasMetadata() + + let remote = try XCTUnwrap(ResourceLocator(protocolEnum: .https, body: "kas.example.com/policy")) + var policy = Policy(type: .remote, body: nil, remote: remote, binding: nil) + let nano = try await createNanoTDF(kas: kasMetadata, policy: &policy, plaintext: Data("slice test".utf8)) + let raw = nano.toData() + + // Create a Data slice with startIndex > 0 + let padded = Data([0xAA, 0xBB, 0xCC, 0xDD]) + raw + let slice = padded.dropFirst(4) + XCTAssertGreaterThan(slice.startIndex, 0) + + let parser = BinaryParser(data: slice) + let parsedHeader = try parser.parseHeader() + let parsedPayload = try parser.parsePayload(config: parsedHeader.payloadSignatureConfig) + XCTAssertEqual(parsedHeader.toData(), nano.header.toData()) + XCTAssertEqual(parsedPayload.ciphertext, nano.payload.ciphertext) + + // Overflow / negative length checks + XCTAssertNil(parser.read(length: -1)) + XCTAssertNil(parser.read(length: Int.max)) + + // NanoTDFCollectionFile.parse with startIndex > 0 + let fileData = NanoTDFCollectionFile.serialize(header: nano.header.toData(), items: Data([1, 2, 3]), itemCount: 1) + let slicedFile = (Data([0xFF, 0xEE, 0xDD]) + fileData).dropFirst(3) + XCTAssertGreaterThan(slicedFile.startIndex, 0) + let parsedFile = try NanoTDFCollectionFile.parse(from: slicedFile) + XCTAssertEqual(parsedFile.header, nano.header.toData()) + XCTAssertEqual(parsedFile.items, Data([1, 2, 3])) + XCTAssertEqual(parsedFile.itemCount, 1) + + // Crafted UInt32.max header length must throw rather than overflow/crash + let hugeHeader = Data([0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00]) + XCTAssertThrowsError(try NanoTDFCollectionFile.parse(from: hugeHeader)) + } + + // MARK: - #5: Non-Zero 3-Byte NanoTDF Nonce + + func testGenerateNonZeroNonceNeverProducesAllZeroBytes() throws { + let helper = CryptoHelper() + for _ in 0 ..< 100 { + let nonce = try helper.generateNonZeroNonce(length: 3) + XCTAssertEqual(nonce.count, 3) + XCTAssertNotEqual(nonce, Data([0, 0, 0])) + } + } + + // MARK: - #6: addSignatureToNanoTDF Curve Validation + + func testAddSignatureRejectsMismatchedCurveAndDefaultsNilToP256() async throws { + let kasKey = P256.KeyAgreement.PrivateKey() + let kasRL = try XCTUnwrap(ResourceLocator(protocolEnum: .https, body: "kas.example.com")) + let kasMetadata = try KasMetadata(resourceLocator: kasRL, publicKey: kasKey.publicKey, curve: .secp256r1) + var policy = Policy(type: .remote, body: nil, remote: kasRL, binding: nil) + var nano = try await createNanoTDF(kas: kasMetadata, policy: &policy, plaintext: Data("hi".utf8)) + + let signingKey = P256.Signing.PrivateKey() + let mismatchedConfig = SignatureAndPayloadConfig(signed: true, signatureCurve: .secp384r1, payloadCipher: .aes256GCM128) + do { + try await addSignatureToNanoTDF(nanoTDF: &nano, privateKey: signingKey, config: mismatchedConfig) + XCTFail("Expected unsupportedCurve for P-384 config with P-256 key") + } catch CryptoHelperError.unsupportedCurve {} + + let nilCurveConfig = SignatureAndPayloadConfig(signed: false, signatureCurve: nil, payloadCipher: .aes256GCM128) + try await addSignatureToNanoTDF(nanoTDF: &nano, privateKey: signingKey, config: nilCurveConfig) + XCTAssertTrue(nano.header.payloadSignatureConfig.signed) + XCTAssertEqual(nano.header.payloadSignatureConfig.signatureCurve, .secp256r1) + } + + // MARK: - #7 & #12: Policy Binding Verification & v12 KeyStore Lookup + + func testNanoTDFDecryptVerifiesPolicyBindingAndSupportsParsedV12KeyStoreLookup() async throws { + let keyStore = KeyStore(curve: .secp256r1) + let kasService = KASService(keyStore: keyStore, baseURL: URL(string: "https://kas.example.com")!) + let kasMetadata = try await kasService.generateKasMetadata() + + let policyBody = EmbeddedPolicyBody(body: Data("classification:secret".utf8)) + var policy = Policy(type: .embeddedPlaintext, body: policyBody, remote: nil, binding: nil) + let plaintext = Data("protected payload".utf8) + let nano = try await createNanoTDF(kas: kasMetadata, policy: &policy, plaintext: plaintext) + + // Round-trip through BinaryParser (v12 wire format leaves kasPublicKey empty!) + let parser = BinaryParser(data: nano.toData()) + let parsedHeader = try parser.parseHeader() + let parsedPayload = try parser.parsePayload(config: parsedHeader.payloadSignatureConfig) + XCTAssertTrue(parsedHeader.payloadKeyAccess.kasPublicKey.isEmpty) + + // #12: KeyStore decryption succeeds on parsed v12 header (single-key store) + let parsedNano = NanoTDF(header: parsedHeader, payload: parsedPayload) + let recovered = try await parsedNano.getPlaintext(using: keyStore) + XCTAssertEqual(recovered, plaintext) + + // #7: Tampering with policy body must fail with invalidPolicyBinding + var tamperedPolicy = parsedHeader.policy + tamperedPolicy.body = EmbeddedPolicyBody(body: Data("classification:public".utf8)) + let tamperedHeader = Header( + payloadKeyAccess: parsedHeader.payloadKeyAccess, + policyBindingConfig: parsedHeader.policyBindingConfig, + payloadSignatureConfig: parsedHeader.payloadSignatureConfig, + policy: tamperedPolicy, + ephemeralPublicKey: parsedHeader.ephemeralPublicKey, + ) + let tamperedNano = NanoTDF(header: tamperedHeader, payload: parsedPayload) + do { + _ = try await tamperedNano.getPlaintext(using: keyStore) + XCTFail("Expected invalidPolicyBinding") + } catch NanoTDFError.invalidPolicyBinding {} + + // Also test CollectionDecryptor rejects tampered binding + do { + _ = try await NanoTDFCollectionDecryptor.withKeyStore(header: tamperedHeader, keyStore: keyStore) + XCTFail("Expected invalidPolicyBinding") + } catch NanoTDFError.invalidPolicyBinding {} + } + + // MARK: - #8 & #34: KASRewrapClient.rewrapNanoTDF Signs with Client Key, Supports P-384, Sends Remote Policy + + func testRewrapNanoTDFSignsWithClientKeySupportsP384AndEncodesRemotePolicy() async throws { + let clientPriv = P384.KeyAgreement.PrivateKey() + let clientKeyPair = EphemeralKeyPair( + privateKey: clientPriv.rawRepresentation, + publicKey: clientPriv.publicKey.compressedRepresentation, + curve: .secp384r1, + ) + let sessionPriv = P384.KeyAgreement.PrivateKey() + let expectedDEK = SymmetricKey(size: .bits256) + + let remoteLocator = try XCTUnwrap(ResourceLocator(protocolEnum: .https, body: "kas.example.com/policy/42")) + let kasLocator = try XCTUnwrap(ResourceLocator(protocolEnum: .https, body: "kas.example.com")) + let header = Header( + kas: kasLocator, + policyBindingConfig: PolicyBindingConfig(ecdsaBinding: false, curve: .secp384r1), + payloadSignatureConfig: SignatureAndPayloadConfig(signed: false, signatureCurve: nil, payloadCipher: .aes256GCM128), + policy: Policy(type: .remote, body: nil, remote: remoteLocator, binding: Data(count: 8)), + ephemeralPublicKey: P384.KeyAgreement.PrivateKey().publicKey.compressedRepresentation, + ) + + var verifiedJWT = false + var seenAlgorithm: String? + var seenPolicyBody: String? + + MockURLProtocol.handler = { request in + let body = try XCTUnwrap(Self.readHTTPBody(request)) + let outer = try XCTUnwrap(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + let jwt = try XCTUnwrap(outer["signed_request_token"] as? String) + let parts = jwt.split(separator: ".") + XCTAssertEqual(parts.count, 3) + + let jwtHeaderData = try XCTUnwrap(Data(base64URLEncoded: parts[0])) + let jwtHeader = try XCTUnwrap(try JSONSerialization.jsonObject(with: jwtHeaderData) as? [String: String]) + XCTAssertEqual(jwtHeader["alg"], "ES384") + + // Verify JWT signature using clientKeyPair's P-384 signing public key + let signingInput = Data("\(parts[0]).\(parts[1])".utf8) + let sigBytes = try XCTUnwrap(Data(base64URLEncoded: parts[2])) + let signingPub = try P384.Signing.PrivateKey(rawRepresentation: clientPriv.rawRepresentation).publicKey + let ecdsaSig = try P384.Signing.ECDSASignature(rawRepresentation: sigBytes) + verifiedJWT = signingPub.isValidSignature(ecdsaSig, for: signingInput) + + let claimsData = try XCTUnwrap(Data(base64URLEncoded: parts[1])) + let claims = try XCTUnwrap(try JSONSerialization.jsonObject(with: claimsData) as? [String: Any]) + let reqBodyStr = try XCTUnwrap(claims["requestBody"] as? String) + let unsigned = try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(reqBodyStr.utf8)) as? [String: Any]) + let reqs = try XCTUnwrap(unsigned["requests"] as? [[String: Any]]) + seenAlgorithm = reqs.first?["algorithm"] as? String + seenPolicyBody = (reqs.first?["policy"] as? [String: Any])?["body"] as? String + + // Wrap DEK with P-384 ECDH + NanoTDF v12 salt + let shared = try sessionPriv.sharedSecretFromKeyAgreement(with: clientPriv.publicKey) + let kek = shared.hkdfDerivedSymmetricKey( + using: SHA256.self, + salt: CryptoConstants.hkdfSalt, + sharedInfo: Data(), + outputByteCount: 32, + ) + let sealed = try expectedDEK.withUnsafeBytes { try AES.GCM.seal($0, using: kek) } + let respObj: [String: Any] = [ + "responses": [[ + "policyId": "policy", + "results": [[ + "keyAccessObjectId": "kao-0", + "status": "permit", + "kasWrappedKey": sealed.combined!.base64EncodedString(), + ]], + ]], + "sessionPublicKey": sessionPriv.publicKey.pemRepresentation, + ] + let resp = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return try (resp, JSONSerialization.data(withJSONObject: respObj)) + } + + let client = try KASRewrapClient( + configuration: OpenTDFConfiguration.forKasConnect("https://kas.example.com"), + oauthToken: "token", + urlSession: MockURLProtocol.makeSession(), + ) + let (wrappedKey, sessionPub) = try await client.rewrapNanoTDF( + header: header.toData(), + parsedHeader: header, + clientKeyPair: clientKeyPair, + ) + XCTAssertTrue(verifiedJWT, "JWT must be signed with clientKeyPair.privateKey") + XCTAssertEqual(seenAlgorithm, "ec:secp384r1") + XCTAssertEqual(seenPolicyBody, remoteLocator.toData().base64EncodedString()) + XCTAssertEqual(sessionPub, sessionPriv.publicKey.compressedRepresentation) + + // Unwrap with P-384 + let unwrapped = try KASRewrapClient.unwrapKey( + wrappedKey: wrappedKey, + sessionPublicKey: sessionPub, + clientPrivateKey: clientKeyPair.privateKey, + ) + XCTAssertEqual( + unwrapped.withUnsafeBytes { Data($0) }, + expectedDEK.withUnsafeBytes { Data($0) }, + ) + } + + // MARK: - #9, #10, #24: SSRF Bypasses, No-Redirect & Bounded HTTP + + func testValidateKasURLBlocksSSRFBypassesAndAcceptsCaseInsensitiveLocalhost() { + // Case-insensitive localhost + XCTAssertNoThrow(try validateKasURL("http://LOCALHOST:8080/kas")) + XCTAssertNoThrow(try validateKasURL("http://LocalHost.:8080/kas")) + + let blocked = [ + // IPv6 zone IDs + "https://[fe80::1%25en0]/kas", + "http://[::1%25lo0]/kas", + // Non-canonical IPv4 (integer, hex, octal, shorthand) + "https://2130706433/kas", + "https://2852039166/kas", + "https://0x7f000001/kas", + "https://0177.0.0.1/kas", + "https://127.1/kas", + "https://10.1/kas", + // Missing CIDRs + "https://0.1.2.3/kas", + "https://100.64.0.1/kas", + "https://100.127.255.254/kas", + "https://224.0.0.1/kas", + "https://240.0.0.1/kas", + "https://255.255.255.255/kas", + "https://[::ffff:127.0.0.1]/kas", + "https://[::ffff:8.8.8.8]/kas", + "https://[64:ff9b::10.0.0.1]/kas", + "https://[ff02::1]/kas", + // Userinfo + "https://user:pass@kas.example.com/kas", + ] + for url in blocked { + XCTAssertThrowsError(try validateKasURL(url), "Expected \(url) to be rejected") + } + } + + func testFetchWellKnownEnforcesSSRFNoRawBodyAndSizeBound() async { + // SSRF URL rejected before hitting URLSession + do { + _ = try await fetchWellKnown(platformURL: "https://169.254.169.254") + XCTFail("Expected invalidURL") + } catch KASDiscoveryError.invalidURL {} catch { + XCTFail("Unexpected error: \(error)") + } + + // Non-2xx must not leak raw server body + MockURLProtocol.handler = { req in + let resp = HTTPURLResponse(url: req.url!, statusCode: 500, httpVersion: nil, headerFields: nil)! + return (resp, Data("INTERNAL-SECRET-STACK-TRACE".utf8)) + } + do { + _ = try await fetchWellKnown(platformURL: "https://platform.example.com", urlSession: MockURLProtocol.makeSession()) + XCTFail("Expected httpError") + } catch let KASDiscoveryError.httpError(code, msg) { + XCTAssertEqual(code, 500) + XCTAssertFalse(msg.contains("INTERNAL-SECRET-STACK-TRACE")) + } catch { + XCTFail("Unexpected error: \(error)") + } + + // Oversized transport response rejected + MockURLProtocol.handler = { req in + let resp = HTTPURLResponse(url: req.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return (resp, Data(repeating: 0x41, count: 4096)) + } + let transport = URLSessionKASTransport(session: MockURLProtocol.makeSession(), maxResponseBytes: 1024) + do { + _ = try await transport.send(URLRequest(url: URL(string: "https://kas.example.com/rewrap")!)) + XCTFail("Expected invalidResponse on oversized response") + } catch KASRewrapError.invalidResponse {} catch { + XCTFail("Unexpected error: \(error)") + } + } + + func testKASServiceRewrapKeyRejectsSSRFURL() async { + let keyStore = KeyStore(curve: .secp256r1) + let service = KASService( + keyStore: keyStore, + baseURL: URL(string: "https://169.254.169.254")!, + credential: KASCredential(clientId: "c", token: "secret-bearer"), + ) + do { + _ = try await service.rewrapKey(ephemeralPublicKey: Data(count: 33), encryptedSessionKey: Data(count: 44)) + XCTFail("Expected invalidRequest for SSRF baseURL") + } catch KASServiceError.invalidRequest {} catch { + XCTFail("Unexpected error: \(error)") + } + } + + // MARK: - #11: Atomic One-Time Key Enforcement & Deterministic KeyID + + func testProcessKeyAccessWithKeyIdentifierIsAtomicUnderConcurrency() async throws { + let keyStore = KeyStore(curve: .secp256r1) + let kasService = KASService(keyStore: keyStore, baseURL: URL(string: "https://kas.example.com")!) + let kasPair = await keyStore.generateKeyPair() + await keyStore.store(keyPair: kasPair) + + let clientPriv = P256.KeyAgreement.PrivateKey() + let kasPriv = try P256.KeyAgreement.PrivateKey(rawRepresentation: kasPair.privateKey) + let shared = try kasPriv.sharedSecretFromKeyAgreement(with: clientPriv.publicKey) + let primaryKey = shared.hkdfDerivedSymmetricKey( + using: SHA256.self, + salt: CryptoConstants.hkdfSaltV12, + sharedInfo: Data(), + outputByteCount: 32, + ) + let sealed = try AES.GCM.seal(Data(repeating: 0x42, count: 16), using: primaryKey) + let encryptedKey = sealed.combined! + + // Launch 8 concurrent rewraps against the same one-time key; exactly 1 must succeed. + var successes = 0 + var keyIDs: [UUID] = [] + await withTaskGroup(of: Result<(Data, UUID), Error>.self) { group in + for _ in 0 ..< 8 { + group.addTask { + do { + let res = try await kasService.processKeyAccessWithKeyIdentifier( + ephemeralPublicKey: clientPriv.publicKey.compressedRepresentation, + encryptedKey: encryptedKey, + kasPublicKey: kasPair.publicKey, + ) + return .success(res) + } catch { + return .failure(error) + } + } + } + for await result in group { + if case let .success((_, id)) = result { + successes += 1 + keyIDs.append(id) + } + } + } + XCTAssertEqual(successes, 1, "One-time key must succeed at most once under concurrency") + + // Re-insert same key and verify deterministic UUID + await keyStore.store(keyPair: kasPair) + let (_, secondID) = try await kasService.processKeyAccessWithKeyIdentifier( + ephemeralPublicKey: clientPriv.publicKey.compressedRepresentation, + encryptedKey: encryptedKey, + kasPublicKey: kasPair.publicKey, + ) + XCTAssertEqual(keyIDs.first, secondID) + } + + // MARK: - #13, #14, #31: TDF Policy Binding, Algorithm/Key Size & JSON/CBOR Hardening + + func testTDFDecryptorVerifiesPolicyBindingAndKeyBitCount() throws { + let rsa = try TDFSegmentedPayloadTests.makeRSAKeyPair() + let kasInfo = TDFKasInfo(url: URL(string: "https://kas.example.com/kas")!, publicKeyPEM: rsa.publicKeyPEM, kid: "r1") + let policy = try TDFPolicy(json: Data(#"{"uuid":"p1","body":{"dataAttributes":[],"dissem":[]}}"#.utf8)) + let config = TDFEncryptionConfiguration(kas: kasInfo, policy: policy, keySize: .bits256) + let result = try TDFEncryptor().encrypt(plaintext: Data("hello".utf8), configuration: config) + + // Tamper policy string -> policyBindingFailed + var tamperedManifest = result.container.manifest + tamperedManifest.encryptionInformation.policy = Data(#"{"uuid":"evil","body":{"dataAttributes":[],"dissem":[]}}"#.utf8).base64EncodedString() + let tamperedContainer = TDFContainer(manifest: tamperedManifest, payload: result.container.payload) + XCTAssertThrowsError(try TDFDecryptor().decrypt(container: tamperedContainer, symmetricKey: result.symmetricKey)) { error in + XCTAssertEqual(error as? TDFDecryptError, .policyBindingFailed) + } + + // Mismatched key size (128-bit key with AES-256-GCM manifest) -> keySizeMismatch + let key128 = SymmetricKey(size: .bits128) + XCTAssertThrowsError(try TDFDecryptor().decrypt(container: result.container, symmetricKey: key128)) { error in + XCTAssertEqual(error as? TDFDecryptError, .keySizeMismatch(expected: 256, actual: 128)) + } + } + + func testTDFJSONAndCBORDecryptorsVerifyPolicyBindingIntegrityAndRejectSplits() throws { + let ecKey = P256.KeyAgreement.PrivateKey() + let policy = try TDFPolicy(json: Data(#"{"uuid":"u","body":{"dataAttributes":[],"dissem":[]}}"#.utf8)) + + // TDF-JSON: tamper policy + let jsonRes = try TDFJSONBuilder() + .kasURL(URL(string: "https://kas.example.com")!) + .kasPublicKey(ecKey.publicKey.pemRepresentation) + .policy(policy) + .encrypt(plaintext: Data("json secret".utf8)) + + var badJSONEncInfo = jsonRes.container.encryptionInformation + badJSONEncInfo.policy = Data(#"{"uuid":"tampered"}"#.utf8).base64EncodedString() + let badJSONEnv = TDFJSONEnvelope( + tdf: "json", + version: "1.0.0", + manifest: TDFJSONManifest(encryptionInformation: badJSONEncInfo), + payload: jsonRes.container.envelope.payload, + ) + let badJSONContainer = TDFJSONContainer(envelope: badJSONEnv, payloadData: jsonRes.container.payloadData) + XCTAssertThrowsError(try TDFJSONDecryptor().decrypt(container: badJSONContainer, symmetricKey: jsonRes.symmetricKey)) + XCTAssertThrowsError(try TDFJSONDecryptor().decrypt(container: badJSONContainer, privateKeyPEM: ecKey.pemRepresentation)) + + // TDF-JSON: payload.length mismatch rejected on decodePayloadValue + var mismatchedPayload = jsonRes.container.envelope.payload + mismatchedPayload.length = 999 + let mismatchedEnv = TDFJSONEnvelope( + tdf: "json", + version: "1.0.0", + manifest: jsonRes.container.manifest, + payload: mismatchedPayload, + ) + XCTAssertThrowsError(try mismatchedEnv.decodePayloadValue()) + + // TDF-CBOR: tamper integrity root signature + let cborRes = try TDFCBORBuilder() + .kasURL(URL(string: "https://kas.example.com")!) + .kasPublicKey(ecKey.publicKey.pemRepresentation) + .policy(policy) + .encrypt(plaintext: Data("cbor secret".utf8)) + + var badCBOREncInfo = cborRes.container.encryptionInformation + badCBOREncInfo.integrityInformation?.rootSignature.sig = Data(count: 32).base64EncodedString() + let badCBOREnv = TDFCBOREnvelope( + manifest: TDFCBORManifest(encryptionInformation: badCBOREncInfo), + payload: cborRes.container.envelope.payload, + ) + XCTAssertThrowsError(try TDFCBORDecryptor().decrypt(container: TDFCBORContainer(envelope: badCBOREnv), symmetricKey: cborRes.symmetricKey)) + + // TDF-CBOR: reject multi-split manifest + var splitEncInfo = cborRes.container.encryptionInformation + var kao1 = splitEncInfo.keyAccess[0] + kao1.sid = "split-1" + var kao2 = splitEncInfo.keyAccess[0] + kao2.sid = "split-2" + splitEncInfo.keyAccess = [kao1, kao2] + let splitEnv = TDFCBOREnvelope(manifest: TDFCBORManifest(encryptionInformation: splitEncInfo), payload: cborRes.container.envelope.payload) + XCTAssertThrowsError(try TDFCBORDecryptor().decrypt(container: TDFCBORContainer(envelope: splitEnv), privateKeyPEM: ecKey.pemRepresentation)) + } + + func testECWrapUnwrapSupportsP384AndP521() throws { + let dek = SymmetricKey(size: .bits256) + let p384 = P384.KeyAgreement.PrivateKey() + let wrapped384 = try TDFCrypto.wrapSymmetricKeyWithEC(publicKeyPEM: p384.publicKey.pemRepresentation, symmetricKey: dek, curve: .p384) + let unwrapped384 = try TDFCrypto.unwrapSymmetricKeyWithEC( + privateKeyPEM: p384.pemRepresentation, + wrappedKey: wrapped384.wrappedKey, + ephemeralPublicKey: wrapped384.ephemeralPublicKey, + ) + XCTAssertEqual(TDFCrypto.data(from: unwrapped384), TDFCrypto.data(from: dek)) + + let p521 = P521.KeyAgreement.PrivateKey() + let wrapped521 = try TDFCrypto.wrapSymmetricKeyWithEC(publicKeyPEM: p521.publicKey.pemRepresentation, symmetricKey: dek, curve: .p521) + let unwrapped521 = try TDFCrypto.unwrapSymmetricKeyWithEC( + privateKeyPEM: p521.pemRepresentation, + wrappedKey: wrapped521.wrappedKey, + ephemeralPublicKey: wrapped521.ephemeralPublicKey, + ) + XCTAssertEqual(TDFCrypto.data(from: unwrapped521), TDFCrypto.data(from: dek)) + } + + // MARK: - #15: StreamingTDFCrypto Integrity & No Premature Plaintext Writes + + func testStreamingMultiSegmentVerifiesHashesAndWritesNoPlaintextOnFailure() throws { + let key = SymmetricKey(size: .bits256) + let inputURL = FileManager.default.temporaryDirectory.appendingPathComponent("stream-in-\(UUID().uuidString)") + let encURL = FileManager.default.temporaryDirectory.appendingPathComponent("stream-enc-\(UUID().uuidString)") + let outURL = FileManager.default.temporaryDirectory.appendingPathComponent("stream-out-\(UUID().uuidString)") + defer { + try? FileManager.default.removeItem(at: inputURL) + try? FileManager.default.removeItem(at: encURL) + try? FileManager.default.removeItem(at: outURL) + } + + try Data("segment-one-data|segment-two-data".utf8).write(to: inputURL) + try Data().write(to: encURL) + try Data().write(to: outURL) + + let inHandle = try FileHandle(forReadingFrom: inputURL) + let encHandle = try FileHandle(forWritingTo: encURL) + let encResult = try StreamingTDFCrypto.encryptPayloadStreamingMultiSegment( + inputHandle: inHandle, + outputHandle: encHandle, + symmetricKey: key, + segmentSizes: [16, 17], + ) + try inHandle.close() + try encHandle.close() + + // Corrupt segment 1's expected hash while leaving segment 0 valid + var tamperedSegments = encResult.segments + tamperedSegments[1] = StreamingTDFCrypto.EncryptedSegment( + segmentIndex: 1, + plaintextSize: tamperedSegments[1].plaintextSize, + encryptedSize: tamperedSegments[1].encryptedSize, + hash: Data(repeating: 0x00, count: 16).base64EncodedString(), + ) + + let readEnc = try FileHandle(forReadingFrom: encURL) + let outHandle = try FileHandle(forWritingTo: outURL) + XCTAssertThrowsError(try StreamingTDFCrypto.decryptPayloadStreamingMultiSegment( + inputHandle: readEnc, + outputHandle: outHandle, + segments: tamperedSegments, + symmetricKey: key, + )) + try readEnc.close() + try outHandle.close() + + // Output file MUST remain empty (no unverified segment 0 plaintext leaked) + let written = try Data(contentsOf: outURL) + XCTAssertTrue(written.isEmpty, "No plaintext should be written to outputHandle when a later segment fails") + } + + // MARK: - #16: ZIP Archive Caps + + func testArchiveReaderWritePayloadEnforcesMaxSize() throws { + let manifest = TDFManifest( + schemaVersion: "4.3.0", + payload: TDFPayloadDescriptor(type: .reference, url: "0.payload", protocolValue: .zip, isEncrypted: true), + encryptionInformation: TDFEncryptionInformation( + type: .split, + keyAccess: [], + method: TDFMethodDescriptor(algorithm: "AES-256-GCM", iv: ""), + policy: "e30=", + ), + ) + let archiveData = try TDFArchiveWriter().buildArchive(manifest: manifest, payload: Data(repeating: 0x42, count: 1024)) + let reader = try TDFArchiveReader(data: archiveData) + + let outURL = FileManager.default.temporaryDirectory.appendingPathComponent("zip-out-\(UUID().uuidString)") + try Data().write(to: outURL) + defer { try? FileManager.default.removeItem(at: outURL) } + let handle = try FileHandle(forWritingTo: outURL) + defer { try? handle.close() } + + XCTAssertThrowsError(try reader.writePayload(to: handle, maxSize: 100)) { error in + XCTAssertEqual(error as? TDFArchiveError, .payloadTooLarge) + } + } + + // MARK: - #17, #19, #29: CBOR Hardening, Slices & Round-Trip Fidelity + + func testCBORRejectsDeepNestingHugeReadNAndHandlesSlicesAndOptionalFields() throws { + // #19: hasMagicBytes on Data slice with startIndex > 0 + let cborSlice = Data([0x00, 0x01, 0xD9, 0xD9, 0xF7, 0xA0]).dropFirst(2) + XCTAssertGreaterThan(cborSlice.startIndex, 0) + XCTAssertTrue(TDFCBOREnvelope.hasMagicBytes(cborSlice)) + + // #17: Deeply nested CBOR array (depth 100) rejected cleanly without stack overflow + var deeplyNested = Data(TDF_CBOR_MAGIC) + deeplyNested.append(contentsOf: [UInt8](repeating: 0x81, count: 100)) + deeplyNested.append(0x00) + XCTAssertThrowsError(try TDFCBOREnvelope.fromCBORData(deeplyNested)) + + // #17: Crafted huge byte string length (0x5B + UInt64.max) rejected before SwiftCBOR allocates + let hugeBstr = Data(TDF_CBOR_MAGIC + [0x5B, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) + XCTAssertThrowsError(try TDFCBOREnvelope.fromCBORData(hugeBstr)) + + // #29: PEM ephemeralPublicKey, sid, encryptedMetadata preserved; nil encryptedSegmentSizeDefault stays nil + let pem = P256.KeyAgreement.PrivateKey().publicKey.pemRepresentation + let kao = TDFKeyAccessObject( + type: .ecWrapped, + url: "https://kas.example.com", + protocolValue: .kas, + wrappedKey: Data(repeating: 1, count: 32).base64EncodedString(), + policyBinding: TDFPolicyBinding(alg: "HS256", hash: Data(repeating: 2, count: 32).base64EncodedString()), + encryptedMetadata: Data("meta".utf8).base64EncodedString(), + kid: "k1", + sid: "split-alpha", + schemaVersion: "1.0", + ephemeralPublicKey: pem, + ) + let integrity = TDFIntegrityInformation( + rootSignature: TDFRootSignature(alg: "HS256", sig: Data(repeating: 3, count: 32).base64EncodedString()), + segmentHashAlg: "GMAC", + segmentSizeDefault: 1024, + encryptedSegmentSizeDefault: nil, + segments: [TDFSegment(hash: Data(repeating: 4, count: 16).base64EncodedString(), segmentSize: 10)], + ) + let env = TDFCBOREnvelope( + manifest: TDFCBORManifest( + encryptionInformation: TDFEncryptionInformation( + type: .split, + keyAccess: [kao], + method: TDFMethodDescriptor(algorithm: "AES-256-GCM", iv: Data(count: 12).base64EncodedString()), + integrityInformation: integrity, + policy: Data("{}".utf8).base64EncodedString(), + ), + ), + payload: TDFBinaryPayload(value: Data(repeating: 5, count: 38)), + ) + let encoded = try env.toCBORData() + let decoded = try TDFCBOREnvelope.fromCBORData(encoded) + let decodedKAO = try XCTUnwrap(decoded.manifest.encryptionInformation.keyAccess.first) + XCTAssertEqual(decodedKAO.ephemeralPublicKey, pem) + XCTAssertEqual(decodedKAO.sid, "split-alpha") + XCTAssertEqual(decodedKAO.encryptedMetadata, Data("meta".utf8).base64EncodedString()) + XCTAssertNil(decoded.manifest.encryptionInformation.integrityInformation?.encryptedSegmentSizeDefault) + } + + // MARK: - #20: Constant-Time Truncated GCM Tags Match 128-Bit Prefix + + func testTruncatedGCMModesMatchCryptoKitTagPrefixAndRejectTampering() throws { + let key = SymmetricKey(size: .bits256) + let iv = Data([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) + let plaintext = Data("constant-time truncated GCM test payload".utf8) + let full = try AES.GCM.seal(plaintext, using: key, nonce: AES.GCM.Nonce(data: iv)) + + for cipher in [Cipher.aes256GCM64, .aes256GCM96, .aes256GCM104, .aes256GCM112, .aes256GCM120] { + let (ct, tag) = try CryptoHelper.encryptNanoTDF(cipher: cipher, key: key, iv: iv, plaintext: plaintext) + XCTAssertEqual(ct, full.ciphertext) + XCTAssertEqual(tag, Data(full.tag.prefix(cipher.tagSize))) + + let opened = try CryptoHelper.decryptNanoTDF(cipher: cipher, key: key, iv: iv, ciphertext: ct, tag: tag) + XCTAssertEqual(opened, plaintext) + + var badTag = tag + badTag[badTag.count - 1] ^= 0x01 + XCTAssertThrowsError(try CryptoHelper.decryptNanoTDF(cipher: cipher, key: key, iv: iv, ciphertext: ct, tag: badTag)) + } + } + + // MARK: - #21, #22, #33: Length Safety, Strict BinaryParser, SharedResourceDirectory + + func testEmbeddedPolicyLengthAndBinaryParserStrictnessAndSharedResourceDirectory() throws { + // #21: EmbeddedPolicyBody > 65535 throws on serializedData and does not trap on toData + let hugePolicy = EmbeddedPolicyBody(body: Data(count: 70000)) + XCTAssertThrowsError(try hugePolicy.serializedData()) { error in + XCTAssertEqual(error as? NanoTDFError, .policyTooLarge(70000)) + } + let clamped = hugePolicy.toData() + XCTAssertEqual(clamped.count, 2 + Int(UInt16.max)) + + // #22: Unknown identifierType (e.g., 0x40 | 0x01 = 0x41) rejected + var badIdData = Data() + badIdData.append(Header.magicNumber) + badIdData.append(Header.versionV12) + badIdData.append(0x41) // identifierType = 4 (invalid), protocol = https + badIdData.append(3) + badIdData.append(Data("kas".utf8)) + XCTAssertThrowsError(try BinaryParser(data: badIdData).parseHeader()) + + // #33: sharedResourceDirectory (0xFF -> 0x0F) round-trips through BinaryParser + let srd = try XCTUnwrap(ResourceLocator(protocolEnum: .sharedResourceDirectory, body: "shared/dir")) + let header = Header( + kas: srd, + policyBindingConfig: PolicyBindingConfig(ecdsaBinding: false, curve: .secp256r1), + payloadSignatureConfig: SignatureAndPayloadConfig(signed: false, signatureCurve: nil, payloadCipher: .aes256GCM128), + policy: Policy(type: .remote, body: nil, remote: srd, binding: Data(count: 8)), + ephemeralPublicKey: Data(count: 33), + ) + let parsed = try BinaryParser(data: header.toData()).parseHeader() + XCTAssertEqual(parsed.kas.protocolEnum, .sharedResourceDirectory) + XCTAssertEqual(parsed.kas.body, "shared/dir") + } + + // MARK: - #23 & #32: KeyStore totalBytesStored & PublicKeyStore Atomic Deserialize + + func testKeyStoreTotalBytesStoredAndPublicKeyStoreAtomicDeserialize() async throws { + let store = KeyStore(curve: .secp256r1) + let pair = await store.generateKeyPair() + await store.store(keyPair: pair) + await store.store(keyPair: pair) // overwrite must not double-count + let expectedSingle = Curve.secp256r1.publicKeyLength + Curve.secp256r1.privateKeyLength + let bytesAfterOverwrite = await store.totalBytesStored + XCTAssertEqual(bytesAfterOverwrite, expectedSingle) + + let serialized = await store.serialize() + let restored = KeyStore(curve: .secp256r1) + try await restored.deserialize(from: serialized) + let restoredBytes = await restored.totalBytesStored + XCTAssertEqual(restoredBytes, expectedSingle) + + try await restored.removeKeyPair(keyID: KeyPairIdentifier(publicKey: pair.publicKey)) + let afterRemoveBytes = await restored.totalBytesStored + XCTAssertEqual(afterRemoveBytes, 0) + + // #23: PublicKeyStore preserves existing keys if deserialize fails + let pubStore = PublicKeyStore(curve: .secp256r1) + await pubStore.addPublicKey(pair.publicKey) + do { + try await pubStore.deserialize(from: Data([0x00, 0x00, 0x00, 0x00, 0x05])) // truncated + XCTFail("Expected invalidData") + } catch {} + let keysAfterFailedDeserialize = await pubStore.publicKeys + XCTAssertEqual(keysAfterFailedDeserialize, [pair.publicKey]) + } + + // MARK: - #25: Numeric KAO Ordering & Unknown KAO ID Rejection + + func testRewrapAndUnwrapTDFSharesSortsNumericallyAndRejectsUnknownKAOIDs() async throws { + let dek = SymmetricKey(size: .bits256) + let entries = (0 ..< 12).map { i in + TDFKeyAccessObject( + type: .ecWrapped, + url: "https://kas.example.com/kas", + protocolValue: .kas, + wrappedKey: Data(repeating: UInt8(i), count: 32).base64EncodedString(), + policyBinding: TDFPolicyBinding(alg: "HS256", hash: "b"), + kid: "k", + sid: "split-\(i)", + ) + } + let manifest = TDFManifest( + schemaVersion: "4.3.0", + payload: TDFPayloadDescriptor(type: .reference, url: "0.payload", protocolValue: .zip, isEncrypted: true), + encryptionInformation: TDFEncryptionInformation( + type: .split, + keyAccess: entries, + method: TDFMethodDescriptor(algorithm: "AES-256-GCM", iv: ""), + policy: Data("{}".utf8).base64EncodedString(), + ), + ) + + MockURLProtocol.handler = { req in + let body = try XCTUnwrap(Self.readHTTPBody(req)) + let outer = try XCTUnwrap(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + let jwt = try XCTUnwrap(outer["signed_request_token"] as? String) + let parts = jwt.split(separator: ".") + let claims = try XCTUnwrap(try JSONSerialization.jsonObject(with: XCTUnwrap(Data(base64URLEncoded: parts[1]))) as? [String: Any]) + let unsigned = try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(XCTUnwrap(claims["requestBody"] as? String).utf8)) as? [String: Any]) + let clientPub = try P256.KeyAgreement.PublicKey(pemRepresentation: XCTUnwrap(unsigned["clientPublicKey"] as? String)) + + let sessionKey = P256.KeyAgreement.PrivateKey() + let kek = try sessionKey.sharedSecretFromKeyAgreement(with: clientPub).hkdfDerivedSymmetricKey( + using: SHA256.self, + salt: KASRewrapClient.standardTDFSessionSalt, + sharedInfo: Data(), + outputByteCount: 32, + ) + // Return results in reverse order + let results: [[String: Any]] = try (0 ..< 12).reversed().map { i in + let sealed = try dek.withUnsafeBytes { try AES.GCM.seal($0, using: kek) } + return [ + "keyAccessObjectId": "kao-\(i)", + "status": "permit", + "kasWrappedKey": sealed.combined!.base64EncodedString(), + ] + } + let payload: [String: Any] = [ + "responses": [["policyId": "policy", "results": results]], + "sessionPublicKey": sessionKey.publicKey.pemRepresentation, + ] + let resp = HTTPURLResponse(url: req.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return try (resp, JSONSerialization.data(withJSONObject: payload)) + } + + let client = try KASRewrapClient( + configuration: OpenTDFConfiguration.forKasConnect("https://kas.example.com"), + oauthToken: "t", + urlSession: MockURLProtocol.makeSession(), + ) + let shares = try await client.rewrapAndUnwrapTDFShares(manifest: manifest) + // Must be sorted numerically: split-0, split-1, split-2, ..., split-10, split-11 (not split-10 before split-2) + XCTAssertEqual(shares.map(\.sid), (0 ..< 12).map { "split-\($0)" }) + + // Foreign KAO ID in rewrapTDF must be rejected + MockURLProtocol.handler = { req in + let payload: [String: Any] = [ + "responses": [[ + "policyId": "policy", + "results": [[ + "keyAccessObjectId": "kao-999", + "status": "permit", + "kasWrappedKey": Data(repeating: 1, count: 44).base64EncodedString(), + ]], + ]], + "sessionPublicKey": P256.KeyAgreement.PrivateKey().publicKey.pemRepresentation, + ] + let resp = HTTPURLResponse(url: req.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return try (resp, JSONSerialization.data(withJSONObject: payload)) + } + do { + _ = try await client.rewrapTDF(manifest: manifest, clientPrivateKey: P256.KeyAgreement.PrivateKey()) + XCTFail("Expected invalidResponse for foreign KAO ID") + } catch KASRewrapError.invalidResponse {} + } + + // MARK: - #27 & #38: TDFFormatDetector CBOR & Bounded File Read + + func testFormatDetectorDetectsCBORWithDetailsAndBoundsJSONFiles() throws { + let cborBytes = Data([0xD9, 0xD9, 0xF7, 0xA1, 0x01, 0x64, 0x63, 0x62, 0x6F, 0x72]) + let details = TDFFormatDetector.detectWithDetails(from: cborBytes) + XCTAssertEqual(details?.format, .cbor) + XCTAssertEqual(details?.confidence, .definitive) + XCTAssertEqual(details?.method, .magicBytes) + + // Large file starting with '{' beyond maxJSONDetectionSize returns nil cleanly + let largeURL = FileManager.default.temporaryDirectory.appendingPathComponent("huge-\(UUID().uuidString).tdf") + defer { try? FileManager.default.removeItem(at: largeURL) } + FileManager.default.createFile(atPath: largeURL.path, contents: Data("{".utf8)) + let handle = try FileHandle(forUpdating: largeURL) + try handle.truncate(atOffset: UInt64(TDFFormatDetector.maxJSONDetectionSize + 1024)) + try handle.close() + XCTAssertNil(TDFFormatDetector.detect(from: largeURL)) + } + + // MARK: - #30: Overflow-Safe SegmentSize in TDFEncryptor + + func testEncryptRejectsOverflowingSegmentSizeWithoutTrapping() throws { + let rsa = try TDFSegmentedPayloadTests.makeRSAKeyPair() + let kasInfo = TDFKasInfo(url: URL(string: "https://kas.example.com/kas")!, publicKeyPEM: rsa.publicKeyPEM, kid: "r1") + let policy = try TDFPolicy(json: Data(#"{"uuid":"u","body":{"dataAttributes":[],"dissem":[]}}"#.utf8)) + let config = TDFEncryptionConfiguration(kas: kasInfo, policy: policy) + + XCTAssertThrowsError(try TDFEncryptor().encrypt( + plaintext: Data("hello".utf8), + configuration: config, + segmentSize: Int.max, + )) + let ok = try TDFEncryptor().encrypt( + plaintext: Data("hello".utf8), + configuration: config, + segmentSize: Int.max - 28, + ) + XCTAssertEqual(try TDFDecryptor().decrypt(container: ok.container, symmetricKey: ok.symmetricKey), Data("hello".utf8)) + } + + // MARK: - #35: KASBulkRewrap Rejects Zero-Byte DEK + + func testBulkRewrapRejectsZeroByteDEK() async throws { + let sessionPriv = P256.KeyAgreement.PrivateKey() + let transport = ZeroByteDEKTransport(sessionKey: sessionPriv) + let client = try KASRewrapClient( + configuration: OpenTDFConfiguration.forKasConnect("https://kas.example.com"), + oauthToken: "t", + transport: transport, + ) + let manifest = TDFManifest( + schemaVersion: "4.3.0", + payload: TDFPayloadDescriptor(type: .reference, url: "0.payload", protocolValue: .zip, isEncrypted: true), + encryptionInformation: TDFEncryptionInformation( + type: .split, + keyAccess: [TDFKeyAccessObject( + type: .ecWrapped, + url: "https://kas.example.com/kas", + protocolValue: .kas, + wrappedKey: Data(repeating: 1, count: 32).base64EncodedString(), + policyBinding: TDFPolicyBinding(alg: "HS256", hash: "b"), + kid: "k", + ephemeralPublicKey: P256.KeyAgreement.PrivateKey().publicKey.pemRepresentation, + )], + method: TDFMethodDescriptor(algorithm: "AES-256-GCM", iv: ""), + policy: Data("{}".utf8).base64EncodedString(), + ), + ) + let outcomes = try await client.rewrapAndUnwrapTDFs([manifest]) + XCTAssertEqual(outcomes.count, 1) + guard case .failed(.unwrapFailed) = outcomes[0] else { + return XCTFail("Expected .failed(.unwrapFailed) for 0-byte DEK, got \(outcomes[0])") + } + } + + // MARK: - Helpers + + private static func readHTTPBody(_ request: URLRequest) -> Data? { + if let body = request.httpBody { + return body + } + guard let stream = request.httpBodyStream else { return nil } + stream.open() + defer { stream.close() } + var data = Data() + var buf = [UInt8](repeating: 0, count: 4096) + while stream.hasBytesAvailable { + let n = stream.read(&buf, maxLength: buf.count) + if n <= 0 { + break + } + data.append(buf, count: n) + } + return data + } +} + +private actor ZeroByteDEKTransport: KASRewrapTransport { + let sessionKey: P256.KeyAgreement.PrivateKey + init(sessionKey: P256.KeyAgreement.PrivateKey) { + self.sessionKey = sessionKey + } + + func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let body = request.httpBody ?? Data() + let outer = try XCTUnwrap(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + let jwt = try XCTUnwrap(outer["signed_request_token"] as? String) + let parts = jwt.split(separator: ".") + let claims = try XCTUnwrap(try JSONSerialization.jsonObject(with: XCTUnwrap(Data(base64URLEncoded: parts[1]))) as? [String: Any]) + let unsigned = try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(XCTUnwrap(claims["requestBody"] as? String).utf8)) as? [String: Any]) + let clientPub = try P256.KeyAgreement.PublicKey(pemRepresentation: XCTUnwrap(unsigned["clientPublicKey"] as? String)) + + let kek = try sessionKey.sharedSecretFromKeyAgreement(with: clientPub).hkdfDerivedSymmetricKey( + using: SHA256.self, + salt: KASRewrapClient.standardTDFSessionSalt, + sharedInfo: Data(), + outputByteCount: 32, + ) + // Seal empty 0-byte DEK (produces 28-byte combined box: 12 nonce + 0 ct + 16 tag) + let sealed = try AES.GCM.seal(Data(), using: kek) + let json: [String: Any] = [ + "responses": [[ + "policyId": "policy-0", + "results": [[ + "keyAccessObjectId": "kao-0", + "status": "permit", + "kasWrappedKey": sealed.combined!.base64EncodedString(), + ]], + ]], + "sessionPublicKey": sessionKey.publicKey.pemRepresentation, + ] + let resp = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return try (JSONSerialization.data(withJSONObject: json), resp) + } +} From c39d1e5096597e590d1219f1689f4fa7ecdf369a Mon Sep 17 00:00:00 2001 From: Paul Flynn Date: Sun, 22 Nov 2026 19:35:17 -0500 Subject: [PATCH 2/3] fix: address multi-model PR #70 review findings (Codex, Claude, Grok) - TDFArchive & TDFLoader: stop rejecting Go ZIP64/data-descriptor placeholder entry.uncompressedSize before extraction (fixes swift <-> go X-Test failure); enforce cap on running extracted bytes; make TDFLoader's default parameter defaultPayloadMaxSize so explicit nil remains uncapped. - TDFCBORFormat: track explicit per-frame nesting depth in validateCBORStructure, charge indefinite-string chunks against maxItems, and pass CBOROptions(maximumDepth: 32) to SwiftCBOR. - TDFProcessor & OpenTDFKitCLI: fail closed in bare-DEK decryptEncryptionInfo when keyAccess is empty or multi-split; add TDFDecryptor.decrypt(container: keyShares:) verifying every split share's policy binding; switch CLI to decrypt(container:keyShares:) and withUnwrappedKey(header:symmetricKey:). - KeyStore & KASService: resolve v12 key pairs once in processKeyAccess(header:encryptedKey:kasPublicKey:), restore popped one-time keys on validation/rewrap failure, add mandatory-binding overloads (deprecating unverified overloads), and use RFC 9562 v8 marker. - KASDiscovery: synchronize BoundedHTTPClient start/finish/cancel in a single state machine to prevent pre-registration cancellation hangs; reject trailing-dot numeric IPv4 literals and block ::/96 (except ::1). - StreamingTDFCrypto: compute rootSignature on encrypt, enforce rootSignature on multi-segment decrypt, support HS256 & GMAC segmentHashAlg, and replace temp-file buffering with two-pass verify-then-decrypt. - TDFFormatDetector, NanoTDF & cleanup: bound JSON probe reads directly (no readToEnd TOCTOU), validate Payload.serializedData() actual length, remove redundant checks and stale CryptoSwift comments, and strengthen SecurityAuditRegressionTests. --- OpenTDFKit/KASBulkRewrap.swift | 3 +- OpenTDFKit/KASDiscovery.swift | 80 ++++- OpenTDFKit/KASService.swift | 137 +++++--- OpenTDFKit/KeyStore.swift | 27 +- OpenTDFKit/NanoTDF.swift | 7 +- OpenTDFKit/NanoTDFCollection.swift | 2 +- OpenTDFKit/NanoTDFCollectionDecryptor.swift | 13 +- OpenTDFKit/TDF/StreamingTDFCrypto.swift | 172 +++++++--- OpenTDFKit/TDF/TDFArchive.swift | 11 +- OpenTDFKit/TDF/TDFBuilder.swift | 11 +- OpenTDFKit/TDF/TDFCBORFormat.swift | 68 ++-- OpenTDFKit/TDF/TDFFormatDetector.swift | 9 +- OpenTDFKit/TDF/TDFProcessor.swift | 98 +++++- OpenTDFKitCLI/Commands.swift | 11 +- .../SecurityAuditRegressionTests.swift | 312 +++++++++++++++++- 15 files changed, 770 insertions(+), 191 deletions(-) diff --git a/OpenTDFKit/KASBulkRewrap.swift b/OpenTDFKit/KASBulkRewrap.swift index 81e3dfb..9f63f47 100644 --- a/OpenTDFKit/KASBulkRewrap.swift +++ b/OpenTDFKit/KASBulkRewrap.swift @@ -351,8 +351,7 @@ extension KASRewrapClient { let wrapped = Data(base64Encoded: wrappedBase64), wrapped.count > 28, let sealed = try? AES.GCM.SealedBox(combined: wrapped), - var dek = try? AES.GCM.open(sealed, using: sessionKEK), - !dek.isEmpty + var dek = try? AES.GCM.open(sealed, using: sessionKEK) { defer { dek.secureZero() } return .permitted(SymmetricKey(data: dek)) diff --git a/OpenTDFKit/KASDiscovery.swift b/OpenTDFKit/KASDiscovery.swift index a86f561..0979a7f 100644 --- a/OpenTDFKit/KASDiscovery.swift +++ b/OpenTDFKit/KASDiscovery.swift @@ -223,7 +223,8 @@ private func stripIPv6Brackets(_ host: String) -> String { } private func isNonCanonicalIPv4Literal(_ host: String) -> Bool { - let trimmed = host.hasSuffix(".") ? String(host.dropLast()) : host + let hasTrailingDot = host.hasSuffix(".") + let trimmed = hasTrailingDot ? String(host.dropLast()) : host guard !trimmed.isEmpty else { return false } // IPv6 literals contain colons and are validated by classifyIP. if trimmed.contains(":") { @@ -241,6 +242,10 @@ private func isNonCanonicalIPv4Literal(_ host: String) -> Bool { } return part.allSatisfy { $0.isASCII && $0.isNumber } }) { + // Numeric IPv4 literals with a trailing dot (e.g. "169.254.169.254.") are non-canonical. + if hasTrailingDot { + return true + } // Canonical IPv4 requires exactly 4 decimal octets in 0...255 with no leading zeros. let isCanonicalV4 = parts.count == 4 && parts.allSatisfy { part in if part.count > 1, part.hasPrefix("0") { @@ -255,7 +260,7 @@ private func isNonCanonicalIPv4Literal(_ host: String) -> Bool { // non-canonical numeric IPv4 form. var v4 = in_addr() if trimmed.withCString({ inet_pton(AF_INET, $0, &v4) }) == 1 { - return false + return hasTrailingDot } var legacy = in_addr() if trimmed.withCString({ inet_aton($0, &legacy) }) != 0 { @@ -286,7 +291,8 @@ private func rawAuthorityHost(from urlString: String) -> String? { } private func classifyIP(_ host: String) -> IPLiteral? { - let normalized = stripIPv6Brackets(host) + let stripped = stripIPv6Brackets(host) + let normalized = stripped.hasSuffix(".") ? String(stripped.dropLast()) : stripped var v4 = in_addr() if normalized.withCString({ inet_pton(AF_INET, $0, &v4) }) == 1 { return .v4(withUnsafeBytes(of: v4.s_addr) { Array($0) }) @@ -349,9 +355,13 @@ private func isBlockedIP(_ ip: IPLiteral) -> Bool { case let .v4(o): return isBlockedV4(o) case let .v6(b): - // ::/128 unspecified - if b.allSatisfy({ $0 == 0 }) { - return true + // ::/96 (unspecified :: and deprecated IPv4-compatible IPv6 ::a.b.c.d), + // preserving loopback ::1 (which is permitted for local development). + if b[0 ..< 12].allSatisfy({ $0 == 0 }) { + let isLoopback = b[12] == 0 && b[13] == 0 && b[14] == 0 && b[15] == 1 + if !isLoopback { + return true + } } // ::ffff:0:0/96 (IPv4-mapped IPv6, including ::ffff:127.0.0.1 and ::ffff:169.254.169.254) if b[0 ..< 10].allSatisfy({ $0 == 0 }), b[10] == 0xFF, b[11] == 0xFF { @@ -490,6 +500,7 @@ enum BoundedHTTPError: Error, Sendable { /// a strict upper bound on buffered response bytes to prevent OOM DoS. enum BoundedHTTPClient { static let defaultWellKnownMaxBytes = 1 * 1024 * 1024 // 1 MiB + static let defaultKASRewrapServiceMaxBytes = 1 * 1024 * 1024 // 1 MiB static let defaultKASMaxBytes = 16 * 1024 * 1024 // 16 MiB static func send( @@ -506,18 +517,24 @@ enum BoundedHTTPClient { delegate.start(task: task, continuation: continuation) } } onCancel: { - task.cancel() + delegate.cancel(task: task) } } private final class Delegate: NSObject, URLSessionDataDelegate, @unchecked Sendable { + private enum State { + case idle + case waiting(CheckedContinuation<(Data, HTTPURLResponse), Error>) + case completed(Result<(Data, HTTPURLResponse), Error>) + case delivered + } + private let maxBytes: Int private let lock = NSLock() - private var continuation: CheckedContinuation<(Data, HTTPURLResponse), Error>? + private var state: State = .idle private var httpResponse: HTTPURLResponse? private var buffer = Data() private var overflowed = false - private var finished = false init(maxBytes: Int) { self.maxBytes = maxBytes @@ -527,19 +544,42 @@ enum BoundedHTTPClient { task: URLSessionDataTask, continuation: CheckedContinuation<(Data, HTTPURLResponse), Error>, ) { - lock.withLock { - self.continuation = continuation + let earlyResult: Result<(Data, HTTPURLResponse), Error>? = lock.withLock { + switch state { + case .idle: + state = .waiting(continuation) + return nil + case let .completed(result): + state = .delivered + return result + case .waiting, .delivered: + return nil + } + } + if let earlyResult { + continuation.resume(with: earlyResult) + return } task.resume() } + func cancel(task: URLSessionDataTask) { + task.cancel() + finish(with: .failure(CancellationError())) + } + private func finish(with result: Result<(Data, HTTPURLResponse), Error>) { let cont: CheckedContinuation<(Data, HTTPURLResponse), Error>? = lock.withLock { - guard !finished else { return nil } - finished = true - let c = continuation - continuation = nil - return c + switch state { + case .idle: + state = .completed(result) + return nil + case let .waiting(c): + state = .delivered + return c + case .completed, .delivered: + return nil + } } cont?.resume(with: result) } @@ -579,7 +619,13 @@ enum BoundedHTTPClient { func urlSession(_: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { let exceeded: Bool = lock.withLock { - if overflowed || finished { + if overflowed { + return true + } + if case .completed = state { + return true + } + if case .delivered = state { return true } if buffer.count > maxBytes - data.count { diff --git a/OpenTDFKit/KASService.swift b/OpenTDFKit/KASService.swift index c066ca3..72ad581 100644 --- a/OpenTDFKit/KASService.swift +++ b/OpenTDFKit/KASService.swift @@ -186,7 +186,7 @@ public actor KASService { (data, httpResponse) = try await BoundedHTTPClient.send( request, on: urlSession, - maxBytes: BoundedHTTPClient.defaultWellKnownMaxBytes, + maxBytes: BoundedHTTPClient.defaultKASRewrapServiceMaxBytes, ) } catch BoundedHTTPError.nonHTTPResponse { throw KASServiceError.networkError("Invalid response type") @@ -341,22 +341,20 @@ public actor KASService { return (rewrappedKey: result, newKeyPair: newKeyPair) } - /// Process key access request locally (server-side KAS implementation). - /// When `policyBody` or `policyBinding` is provided, verifies the binding before rewrapping. + /// Process key access request locally (server-side KAS implementation), always verifying + /// the policy binding before rewrapping. public func processKeyAccess( ephemeralPublicKey: Data, encryptedKey: Data, kasPublicKey: Data, - policyBody: Data? = nil, - policyBinding: Data? = nil, + policyBody: Data, + policyBinding: Data, ) async throws -> Data { - // Get the KAS private key corresponding to the KAS public key guard var privateKeyData = await keyStore.getPrivateKey(forPublicKey: kasPublicKey) else { throw KASServiceError.keyNotFound } defer { privateKeyData.secureZero() } - // Use the internal helper to perform the rewrapping let (rewrappedKey, _) = try await rewrapKeyInternal( ephemeralPublicKey: ephemeralPublicKey, encryptedKey: encryptedKey, @@ -368,30 +366,49 @@ public actor KASService { return rewrappedKey } - /// Process a NanoTDF key access request locally, always verifying the header's policy binding. + /// Process key access request locally without policy binding verification. + @available(*, deprecated, message: "Use processKeyAccess(ephemeralPublicKey:encryptedKey:kasPublicKey:policyBody:policyBinding:) or processKeyAccess(header:encryptedKey:kasPublicKey:) to enforce policy binding verification.") + public func processKeyAccess( + ephemeralPublicKey: Data, + encryptedKey: Data, + kasPublicKey: Data, + ) async throws -> Data { + guard var privateKeyData = await keyStore.getPrivateKey(forPublicKey: kasPublicKey) else { + throw KASServiceError.keyNotFound + } + defer { privateKeyData.secureZero() } + + let (rewrappedKey, _) = try await rewrapKeyInternal( + ephemeralPublicKey: ephemeralPublicKey, + encryptedKey: encryptedKey, + privateKeyData: privateKeyData, + ) + + return rewrappedKey + } + + /// Process a NanoTDF key access request locally, resolving v12 headers (which omit `kasPublicKey` + /// on the wire) and always verifying the header's policy binding before rewrapping. public func processKeyAccess( header: Header, encryptedKey: Data, kasPublicKey: Data? = nil, ) async throws -> Data { - let lookupKey = kasPublicKey ?? header.payloadKeyAccess.kasPublicKey - let symmetricKey: SymmetricKey = if !lookupKey.isEmpty { - try await keyStore.derivePayloadSymmetricKey( - kasPublicKey: lookupKey, - tdfEphemeralPublicKey: header.ephemeralPublicKey, - ) - } else { - try await keyStore.derivePayloadSymmetricKey(header: header) + guard let resolved = await keyStore.resolveKeyPair(for: header, explicitPublicKey: kasPublicKey) else { + throw KASServiceError.keyNotFound } + var privateKeyData = resolved.privateKey + defer { privateKeyData.secureZero() } + + let symmetricKey = try keyStore.derivePayloadSymmetricKey( + kasPrivateKeyData: privateKeyData, + tdfEphemeralPublicKey: header.ephemeralPublicKey, + ) do { try header.verifyPolicyBinding(symmetricKey: symmetricKey) } catch { throw KASServiceError.accessDenied } - guard var privateKeyData = await keyStore.getPrivateKey(forPublicKey: lookupKey) else { - throw KASServiceError.keyNotFound - } - defer { privateKeyData.secureZero() } let (rewrappedKey, _) = try await rewrapKeyInternal( ephemeralPublicKey: header.ephemeralPublicKey, encryptedKey: encryptedKey, @@ -434,23 +451,50 @@ public actor KASService { return result == 0 } - /// Process a key access request and report which key was used - /// - Parameters: - /// - ephemeralPublicKey: The ephemeral public key from the requester - /// - encryptedKey: The encrypted session key that needs to be rewrapped - /// - kasPublicKey: The KAS public key - /// - Returns: A tuple containing the rewrapped key data and the ID of the key that was used - /// - Throws: KAS errors - /// Process a key access request atomically (one-time key) and report a deterministic UUID - /// derived from `kasPublicKey`. + /// Atomically processes a one-time key access request, verifies the policy binding, + /// and reports a deterministic RFC 9562 v8 UUID derived from `kasPublicKey`. + /// Restores the key to the store if validation or decryption fails so malformed + /// requests cannot permanently consume a one-time key. public func processKeyAccessWithKeyIdentifier( ephemeralPublicKey: Data, encryptedKey: Data, kasPublicKey: Data, - policyBody: Data? = nil, - policyBinding: Data? = nil, + policyBody: Data, + policyBinding: Data, ) async throws -> (rewrappedKey: Data, keyID: UUID) { - // Atomically pop the one-time key so concurrent callers cannot race and reuse it + try await processKeyAccessWithKeyIdentifierInternal( + ephemeralPublicKey: ephemeralPublicKey, + encryptedKey: encryptedKey, + kasPublicKey: kasPublicKey, + policyBody: policyBody, + policyBinding: policyBinding, + ) + } + + /// Atomically processes a one-time key access request without policy binding verification. + @available(*, deprecated, message: "Use processKeyAccessWithKeyIdentifier(ephemeralPublicKey:encryptedKey:kasPublicKey:policyBody:policyBinding:) to enforce policy binding verification.") + public func processKeyAccessWithKeyIdentifier( + ephemeralPublicKey: Data, + encryptedKey: Data, + kasPublicKey: Data, + ) async throws -> (rewrappedKey: Data, keyID: UUID) { + try await processKeyAccessWithKeyIdentifierInternal( + ephemeralPublicKey: ephemeralPublicKey, + encryptedKey: encryptedKey, + kasPublicKey: kasPublicKey, + policyBody: nil, + policyBinding: nil, + ) + } + + private func processKeyAccessWithKeyIdentifierInternal( + ephemeralPublicKey: Data, + encryptedKey: Data, + kasPublicKey: Data, + policyBody: Data?, + policyBinding: Data?, + ) async throws -> (rewrappedKey: Data, keyID: UUID) { + // Atomically pop the one-time key so concurrent valid callers cannot reuse it. guard var privateKeyData = await keyStore.popPrivateKey(forPublicKey: kasPublicKey) else { throw KASServiceError.keyNotFound } @@ -458,22 +502,27 @@ public actor KASService { let keyID = Self.deterministicUUID(for: kasPublicKey) - let (rewrappedKey, _) = try await rewrapKeyInternal( - ephemeralPublicKey: ephemeralPublicKey, - encryptedKey: encryptedKey, - privateKeyData: privateKeyData, - policyBody: policyBody, - policyBinding: policyBinding, - ) - - return (rewrappedKey: rewrappedKey, keyID: keyID) + do { + let (rewrappedKey, _) = try await rewrapKeyInternal( + ephemeralPublicKey: ephemeralPublicKey, + encryptedKey: encryptedKey, + privateKeyData: privateKeyData, + policyBody: policyBody, + policyBinding: policyBinding, + ) + return (rewrappedKey: rewrappedKey, keyID: keyID) + } catch { + // Restore the key so a malformed or unauthorized request cannot burn a one-time key. + await keyStore.store(keyPair: StoredKeyPair(publicKey: kasPublicKey, privateKey: privateKeyData)) + throw error + } } - /// Derives a deterministic RFC 4122 (version 5 / SHA-256 truncated) UUID from the KAS public key bytes. + /// Derives a deterministic RFC 9562 version 8 (custom SHA-256) UUID from the KAS public key bytes. private static func deterministicUUID(for publicKey: Data) -> UUID { var digest = Array(SHA256.hash(data: publicKey).prefix(16)) - digest[6] = (digest[6] & 0x0F) | 0x50 // version 5 marker - digest[8] = (digest[8] & 0x3F) | 0x80 // RFC 4122 variant + digest[6] = (digest[6] & 0x0F) | 0x80 // RFC 9562 version 8 marker + digest[8] = (digest[8] & 0x3F) | 0x80 // RFC 4122/9562 variant return UUID(uuid: ( digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], diff --git a/OpenTDFKit/KeyStore.swift b/OpenTDFKit/KeyStore.swift index 427fc12..0a5e198 100644 --- a/OpenTDFKit/KeyStore.swift +++ b/OpenTDFKit/KeyStore.swift @@ -275,10 +275,10 @@ public actor KeyStore { recalculateTotalBytesStored() } - /// Resolves the private key for a parsed v12 NanoTDF header (whose wire format omits `kasPublicKey`). + /// Resolves the key pair for a parsed v12 NanoTDF header (whose wire format omits `kasPublicKey`). /// Matches by optional `ResourceLocator.identifier` (exact public key, public key prefix, or SHA-256 prefix), /// or falls back to the sole stored key when the store contains exactly one key. - private func resolveV12PrivateKey(identifier: Data?) -> Data? { + private func resolveV12KeyPair(identifier: Data?) -> (publicKey: Data, privateKey: Data)? { if let identifier, !identifier.isEmpty { var matches: [StoredKeyPair] = [] for (keyID, pair) in keyPairs { @@ -294,15 +294,29 @@ public actor KeyStore { } } if let unique = matches.first { - return unique.privateKey + return (unique.publicKey, unique.privateKey) } } if keyPairs.count == 1, let sole = keyPairs.values.first { - return sole.privateKey + return (sole.publicKey, sole.privateKey) } return nil } + /// Resolves the stored key pair for a NanoTDF header, handling both explicit KAS public keys + /// and parsed v12 headers (whose wire format omits `kasPublicKey`). + func resolveKeyPair(for header: Header, explicitPublicKey: Data? = nil) -> (publicKey: Data, privateKey: Data)? { + let lookupKey = explicitPublicKey ?? header.payloadKeyAccess.kasPublicKey + if !lookupKey.isEmpty { + let identifier = KeyPairIdentifier(publicKey: lookupKey) + guard let pair = keyPairs[identifier] else { + return nil + } + return (pair.publicKey, pair.privateKey) + } + return resolveV12KeyPair(identifier: header.kas.identifier) + } + /// Derives the symmetric key for NanoTDF payload decryption using ECDH. /// This function assumes the KeyStore holds the KAS's private key. /// @@ -319,9 +333,10 @@ public actor KeyStore { } // v12 NanoTDF headers omit the KAS public key on the wire; resolve via identifier or sole key. - guard var kasPrivateKeyData = await resolveV12PrivateKey(identifier: header.kas.identifier) else { + guard let resolved = await resolveV12KeyPair(identifier: header.kas.identifier) else { throw KeyStoreError.keyNotFound("Private key for v12 NanoTDF header not found in this KeyStore.") } + var kasPrivateKeyData = resolved.privateKey defer { kasPrivateKeyData.secureZero() } return try derivePayloadSymmetricKey( kasPrivateKeyData: kasPrivateKeyData, @@ -357,7 +372,7 @@ public actor KeyStore { ) } - private nonisolated func derivePayloadSymmetricKey( + nonisolated func derivePayloadSymmetricKey( kasPrivateKeyData: Data, tdfEphemeralPublicKey: Data, ) throws -> SymmetricKey { diff --git a/OpenTDFKit/NanoTDF.swift b/OpenTDFKit/NanoTDF.swift index a80df85..5bd0623 100644 --- a/OpenTDFKit/NanoTDF.swift +++ b/OpenTDFKit/NanoTDF.swift @@ -562,9 +562,14 @@ public struct Payload: Sendable { } /// Serializes the Payload into its binary `Data` representation, validating that `length` - /// fits within the 24-bit wire format limit (`0xFFFFFF`). + /// matches `iv.count + ciphertext.count + mac.count` and fits within the 24-bit wire limit (`0xFFFFFF`). public func serializedData() throws -> Data { + let actualLength = iv.count + ciphertext.count + mac.count try NanoTDF.validatePayloadLength(Int(length)) + try NanoTDF.validatePayloadLength(actualLength) + guard Int(length) == actualLength else { + throw NanoTDFError.payloadTooLarge(actualLength) + } return toData() } diff --git a/OpenTDFKit/NanoTDFCollection.swift b/OpenTDFKit/NanoTDFCollection.swift index d87d931..7f4d591 100644 --- a/OpenTDFKit/NanoTDFCollection.swift +++ b/OpenTDFKit/NanoTDFCollection.swift @@ -328,7 +328,7 @@ public actor NanoTDFCollection { return CollectionItem(ivCounter: iv, ciphertext: sealed.ciphertext, tag: sealed.tag) } - // For other tag sizes, use CryptoHelper's CryptoSwift path + // For truncated tag sizes, use CryptoHelper's constant-time CommonCrypto CTR + CryptoKit GCM path let (ciphertext, tag) = try CryptoHelper.encryptNanoTDF( cipher: configuration.cipher, key: symmetricKey, diff --git a/OpenTDFKit/NanoTDFCollectionDecryptor.swift b/OpenTDFKit/NanoTDFCollectionDecryptor.swift index 46ad64b..331b628 100644 --- a/OpenTDFKit/NanoTDFCollectionDecryptor.swift +++ b/OpenTDFKit/NanoTDFCollectionDecryptor.swift @@ -9,9 +9,9 @@ import Foundation /// ## Client-Side Usage /// ```swift /// // After KAS rewrap provides the symmetric key -/// let decryptor = NanoTDFCollectionDecryptor.withUnwrappedKey( -/// symmetricKey: unwrappedKey, -/// cipher: .aes256GCM128 +/// let decryptor = try NanoTDFCollectionDecryptor.withUnwrappedKey( +/// header: collectionHeader, +/// symmetricKey: unwrappedKey /// ) /// let plaintext = try await decryptor.decryptItem(item) /// ``` @@ -37,13 +37,14 @@ public actor NanoTDFCollectionDecryptor { // MARK: - Factory Methods - /// Creates a decryptor with an already-unwrapped symmetric key. - /// Use this for client-side decryption after KAS rewrap. + /// Creates a decryptor with an already-unwrapped symmetric key without verifying + /// a collection header's policy binding. /// /// - Parameters: /// - symmetricKey: The unwrapped symmetric key from KAS rewrap /// - cipher: The cipher used for encryption (default: aes256GCM128) /// - Returns: A configured decryptor ready for use + @available(*, deprecated, message: "Use withUnwrappedKey(header:symmetricKey:) so the collection policy binding is verified before decryption.") public static func withUnwrappedKey( symmetricKey: SymmetricKey, cipher: Cipher = .aes256GCM128, @@ -182,7 +183,7 @@ public actor NanoTDFCollectionDecryptor { } } - // For other tag sizes, use CryptoHelper's CryptoSwift path + // For truncated tag sizes, use CryptoHelper's constant-time CommonCrypto CTR + CryptoKit GCM path do { return try CryptoHelper.decryptNanoTDF( cipher: cipher, diff --git a/OpenTDFKit/TDF/StreamingTDFCrypto.swift b/OpenTDFKit/TDF/StreamingTDFCrypto.swift index cec0042..cb3e711 100644 --- a/OpenTDFKit/TDF/StreamingTDFCrypto.swift +++ b/OpenTDFKit/TDF/StreamingTDFCrypto.swift @@ -58,12 +58,15 @@ public enum StreamingTDFCrypto { hash: segmentHash, ) + let rootSig = Data(HMAC.authenticationCode(for: Data(sealed.tag), using: symmetricKey)).base64EncodedString() + let result = StreamingEncryptionResult( iv: Data(nonce), tag: Data(sealed.tag), segments: [segment], totalPlaintextSize: totalPlaintextRead, totalEncryptedSize: totalEncrypted, + rootSignature: rootSig, ) return (encryptedPayload, result) @@ -91,6 +94,7 @@ public enum StreamingTDFCrypto { encryptedPayload.reserveCapacity(totalCapacity) var segments: [EncryptedSegment] = [] + var rawTags: [Data] = [] var totalPlaintextRead: Int64 = 0 var totalEncryptedWritten: Int64 = 0 var segmentIndex = 0 @@ -134,16 +138,18 @@ public enum StreamingTDFCrypto { if firstIV == nil { firstIV = Data(nonce) } - lastTag = Data(sealed.tag) + let tagData = Data(sealed.tag) + lastTag = tagData + rawTags.append(tagData) let segmentStart = encryptedPayload.count encryptedPayload.append(Data(nonce)) encryptedPayload.append(sealed.ciphertext) - encryptedPayload.append(Data(sealed.tag)) + encryptedPayload.append(tagData) let segmentEnd = encryptedPayload.count let segmentEncryptedSize = Int64(segmentEnd - segmentStart) - let segmentHash = Data(sealed.tag).base64EncodedString() + let segmentHash = tagData.base64EncodedString() let segment = EncryptedSegment( segmentIndex: segmentIndex, @@ -166,12 +172,18 @@ public enum StreamingTDFCrypto { throw StreamingCryptoError.invalidSegmentSize } + let rootSig = Data(HMAC.authenticationCode( + for: Data(rawTags.joined()), + using: symmetricKey, + )).base64EncodedString() + let result = StreamingEncryptionResult( iv: ivData, tag: tagData, segments: segments, totalPlaintextSize: totalPlaintextRead, totalEncryptedSize: totalEncryptedWritten, + rootSignature: rootSig, ) return (encryptedPayload, result) @@ -197,13 +209,22 @@ public enum StreamingTDFCrypto { public let segments: [EncryptedSegment] public let totalPlaintextSize: Int64 public let totalEncryptedSize: Int64 - - public init(iv: Data, tag: Data, segments: [EncryptedSegment], totalPlaintextSize: Int64, totalEncryptedSize: Int64) { + public let rootSignature: String? + + public init( + iv: Data, + tag: Data, + segments: [EncryptedSegment], + totalPlaintextSize: Int64, + totalEncryptedSize: Int64, + rootSignature: String? = nil, + ) { self.iv = iv self.tag = tag self.segments = segments self.totalPlaintextSize = totalPlaintextSize self.totalEncryptedSize = totalEncryptedSize + self.rootSignature = rootSignature } } @@ -259,12 +280,15 @@ public enum StreamingTDFCrypto { hash: segmentHash, ) + let rootSig = Data(HMAC.authenticationCode(for: Data(sealed.tag), using: symmetricKey)).base64EncodedString() + return StreamingEncryptionResult( iv: Data(nonce), tag: Data(sealed.tag), segments: [segment], totalPlaintextSize: totalPlaintextRead, totalEncryptedSize: totalEncrypted, + rootSignature: rootSig, ) } @@ -280,6 +304,7 @@ public enum StreamingTDFCrypto { try inputHandle.seek(toOffset: 0) var segments: [EncryptedSegment] = [] + var rawTags: [Data] = [] var totalPlaintextRead: Int64 = 0 var totalEncryptedWritten: Int64 = 0 var segmentIndex = 0 @@ -323,16 +348,18 @@ public enum StreamingTDFCrypto { if firstIV == nil { firstIV = Data(nonce) } - lastTag = Data(sealed.tag) + let tagData = Data(sealed.tag) + lastTag = tagData + rawTags.append(tagData) let segmentStartOffset = try outputHandle.offset() try outputHandle.write(contentsOf: Data(nonce)) try outputHandle.write(contentsOf: sealed.ciphertext) - try outputHandle.write(contentsOf: Data(sealed.tag)) + try outputHandle.write(contentsOf: tagData) let segmentEndOffset = try outputHandle.offset() let segmentEncryptedSize = Int64(segmentEndOffset - segmentStartOffset) - let segmentHash = Data(sealed.tag).base64EncodedString() + let segmentHash = tagData.base64EncodedString() let segment = EncryptedSegment( segmentIndex: segmentIndex, @@ -357,12 +384,18 @@ public enum StreamingTDFCrypto { throw StreamingCryptoError.invalidSegmentSize } + let rootSig = Data(HMAC.authenticationCode( + for: Data(rawTags.joined()), + using: symmetricKey, + )).base64EncodedString() + return StreamingEncryptionResult( iv: ivData, tag: tagData, segments: segments, totalPlaintextSize: totalPlaintextRead, totalEncryptedSize: totalEncryptedWritten, + rootSignature: rootSig, ) } @@ -407,6 +440,27 @@ public enum StreamingTDFCrypto { try outputHandle.write(contentsOf: plaintext) } + private static func computeSegmentSignature( + ivData: Data, + ciphertext: Data, + tagData: Data, + algorithm: String, + symmetricKey: SymmetricKey, + ) throws -> Data { + switch algorithm.uppercased() { + case "GMAC": + return tagData + case "HS256": + var hmac = HMAC(key: symmetricKey) + hmac.update(data: ivData) + hmac.update(data: ciphertext) + hmac.update(data: tagData) + return Data(hmac.finalize()) + default: + throw StreamingCryptoError.integrityCheckFailed + } + } + public static func decryptPayloadStreamingMultiSegment( inputHandle: FileHandle, outputHandle: FileHandle, @@ -414,25 +468,23 @@ public enum StreamingTDFCrypto { symmetricKey: SymmetricKey, chunkSize: Int = defaultChunkSize, rootSignature: String? = nil, + segmentHashAlg: String = "GMAC", ) throws { guard chunkSize > 0 else { throw StreamingCryptoError.invalidChunkSize } guard !segments.isEmpty else { throw StreamingCryptoError.malformedSegment(0) } + // Multi-segment payloads require a rootSignature to prevent segment reordering/dropping. + if segments.count > 1, rootSignature == nil { + throw StreamingCryptoError.integrityCheckFailed + } let startOffset = try inputHandle.offset() let endOffset = try inputHandle.seekToEnd() guard endOffset >= startOffset else { throw StreamingCryptoError.segmentReadFailed } - var currentOffset = startOffset - - // Buffer decrypted plaintext into a temporary file so no unverified plaintext - // is written to `outputHandle` if a later segment, hash, or root signature fails. - let tempURL = FileManager.default.temporaryDirectory - .appendingPathComponent(".opentdf-stream-decrypt-\(UUID().uuidString).tmp") - FileManager.default.createFile(atPath: tempURL.path, contents: nil) - defer { try? FileManager.default.removeItem(at: tempURL) } - let tempHandle = try FileHandle(forUpdating: tempURL) - defer { try? tempHandle.close() } - var rawTags: [Data] = [] - rawTags.reserveCapacity(segments.count) + // Pass 1: authenticate every segment (GCM tag + manifest segment hash) and the + // root signature without writing any unverified plaintext to `outputHandle` or disk. + var currentOffset = startOffset + var segmentSignatures: [Data] = [] + segmentSignatures.reserveCapacity(segments.count) for segment in segments { guard segment.encryptedSize >= 28, @@ -471,19 +523,25 @@ public enum StreamingTDFCrypto { throw StreamingCryptoError.malformedSegment(segment.segmentIndex) } - // Verify segment GMAC hash in constant time + let computedSig = try computeSegmentSignature( + ivData: ivData, + ciphertext: ciphertextAccumulator, + tagData: tagData, + algorithm: segmentHashAlg, + symmetricKey: symmetricKey, + ) guard let expectedHash = Data(base64Encoded: segment.hash), - CryptoHelper.constantTimeEquals(expectedHash, tagData) + 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) - let plaintext = try AES.GCM.open(sealed, using: symmetricKey) + var verifiedPlaintext = try AES.GCM.open(sealed, using: symmetricKey) + verifiedPlaintext.secureZero() - try tempHandle.write(contentsOf: plaintext) - rawTags.append(tagData) + segmentSignatures.append(computedSig) currentOffset += segmentSize } @@ -493,7 +551,7 @@ public enum StreamingTDFCrypto { if let rootSignature { let computedRoot = Data(HMAC.authenticationCode( - for: Data(rawTags.joined()), + for: Data(segmentSignatures.joined()), using: symmetricKey, )) guard let expectedRoot = Data(base64Encoded: rootSignature), @@ -503,14 +561,36 @@ public enum StreamingTDFCrypto { } } - // All segments and integrity checks passed; stream verified plaintext to outputHandle. - try tempHandle.seek(toOffset: 0) - while true { - let chunk = try tempHandle.read(upToCount: chunkSize) ?? Data() - if chunk.isEmpty { - break + // Pass 2: every segment and the root signature passed; stream verified plaintext directly to outputHandle. + currentOffset = startOffset + for segment in segments { + let segmentSizeInt = Int(segment.encryptedSize) + let segmentSize = UInt64(segment.encryptedSize) + try inputHandle.seek(toOffset: currentOffset) + + let ivData = try inputHandle.read(upToCount: 12) ?? Data() + 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 } - try outputHandle.write(contentsOf: chunk) + let tagData = try inputHandle.read(upToCount: 16) ?? Data() + + 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 outputHandle.write(contentsOf: plaintext) + + currentOffset += segmentSize } } @@ -519,14 +599,18 @@ public enum StreamingTDFCrypto { segments: [EncryptedSegment], symmetricKey: SymmetricKey, rootSignature: String? = nil, + segmentHashAlg: String = "GMAC", ) throws -> Data { guard !segments.isEmpty else { throw StreamingCryptoError.malformedSegment(0) } + if segments.count > 1, rootSignature == nil { + throw StreamingCryptoError.integrityCheckFailed + } var plaintext = Data() plaintext.reserveCapacity(encryptedPayload.count) - var rawTags: [Data] = [] - rawTags.reserveCapacity(segments.count) + var segmentSignatures: [Data] = [] + segmentSignatures.reserveCapacity(segments.count) var offset = 0 for segment in segments { @@ -534,17 +618,25 @@ public enum StreamingTDFCrypto { let segmentSize = Int(exactly: segment.encryptedSize), offset <= encryptedPayload.count, segmentSize <= encryptedPayload.count - offset else { + plaintext.secureZero() throw StreamingCryptoError.malformedSegment(segment.segmentIndex) } let start = encryptedPayload.startIndex + offset - let ivData = encryptedPayload[start ..< start + 12] + let ivData = Data(encryptedPayload[start ..< start + 12]) let ciphertextSize = segmentSize - 28 - let ciphertextData = encryptedPayload[start + 12 ..< start + 12 + ciphertextSize] + let ciphertextData = Data(encryptedPayload[start + 12 ..< start + 12 + ciphertextSize]) let tagData = Data(encryptedPayload[start + 12 + ciphertextSize ..< start + segmentSize]) + let computedSig = try computeSegmentSignature( + ivData: ivData, + ciphertext: ciphertextData, + tagData: tagData, + algorithm: segmentHashAlg, + symmetricKey: symmetricKey, + ) guard let expectedHash = Data(base64Encoded: segment.hash), - CryptoHelper.constantTimeEquals(expectedHash, tagData) + CryptoHelper.constantTimeEquals(expectedHash, computedSig) else { plaintext.secureZero() throw StreamingCryptoError.integrityCheckFailed @@ -555,7 +647,7 @@ public enum StreamingTDFCrypto { let segmentPlaintext = try AES.GCM.open(sealed, using: symmetricKey) plaintext.append(segmentPlaintext) - rawTags.append(tagData) + segmentSignatures.append(computedSig) offset += segmentSize } @@ -566,7 +658,7 @@ public enum StreamingTDFCrypto { if let rootSignature { let computedRoot = Data(HMAC.authenticationCode( - for: Data(rawTags.joined()), + for: Data(segmentSignatures.joined()), using: symmetricKey, )) guard let expectedRoot = Data(base64Encoded: rootSignature), diff --git a/OpenTDFKit/TDF/TDFArchive.swift b/OpenTDFKit/TDF/TDFArchive.swift index d1ba2b6..12063f6 100644 --- a/OpenTDFKit/TDF/TDFArchive.swift +++ b/OpenTDFKit/TDF/TDFArchive.swift @@ -153,14 +153,15 @@ public struct TDFArchiveReader { /// Reads the whole payload into memory. /// - Parameter maxSize: Largest payload accepted, in bytes; defaults to /// `TDFArchiveReader.defaultPayloadMaxSize` (pass `nil` to opt out of the cap). - /// Checked against the ZIP header and again while extracting, since the - /// header's size is not trusted; initial buffer reservation is capped so - /// spoofed ZIP headers cannot trigger OOM. + /// Enforced against the running extracted byte count because ZIP header + /// sizes are untrusted (and streaming writers such as Go's `archive/zip` + /// may store a ZIP64/data-descriptor placeholder); initial buffer + /// reservation is capped so spoofed or placeholder sizes cannot trigger OOM. /// - Throws: `TDFArchiveError.payloadTooLarge` when the payload exceeds `maxSize`. public func payloadData(maxSize: Int? = TDFArchiveReader.defaultPayloadMaxSize) throws -> Data { let entry = try payloadEntry() if let maxSize { - guard maxSize >= 0, entry.uncompressedSize <= UInt64(maxSize) else { + guard maxSize >= 0 else { throw TDFArchiveError.payloadTooLarge } } @@ -191,7 +192,7 @@ public struct TDFArchiveReader { ) throws { let entry = try payloadEntry() if let maxSize { - guard maxSize >= 0, entry.uncompressedSize <= UInt64(maxSize) else { + guard maxSize >= 0 else { throw TDFArchiveError.payloadTooLarge } } diff --git a/OpenTDFKit/TDF/TDFBuilder.swift b/OpenTDFKit/TDF/TDFBuilder.swift index 040d105..31b735b 100644 --- a/OpenTDFKit/TDF/TDFBuilder.swift +++ b/OpenTDFKit/TDF/TDFBuilder.swift @@ -17,23 +17,24 @@ public struct TDFLoader { /// Largest payload `load` accepts, in bytes; `nil` for no cap. public let maxPayloadSize: Int? - /// - Parameter maxPayloadSize: Bound for small objects such as metadata - /// TDFs; a larger payload throws `TDFArchiveError.payloadTooLarge`. - public init(maxPayloadSize: Int? = nil) { + /// - Parameter maxPayloadSize: Upper bound on payload bytes read into memory; + /// defaults to `TDFArchiveReader.defaultPayloadMaxSize` (512 MiB). Pass + /// `nil` explicitly to opt out of the cap. + public init(maxPayloadSize: Int? = TDFArchiveReader.defaultPayloadMaxSize) { self.maxPayloadSize = maxPayloadSize } public func load(from data: Data) throws -> TDFContainer { let reader = try TDFArchiveReader(data: data) let manifest = try reader.manifest() - let payload = try reader.payloadData(maxSize: maxPayloadSize ?? TDFArchiveReader.defaultPayloadMaxSize) + let payload = try reader.payloadData(maxSize: maxPayloadSize) return TDFContainer(manifest: manifest, payload: payload) } public func load(from url: URL) throws -> TDFContainer { let reader = try TDFArchiveReader(url: url) let manifest = try reader.manifest() - let payload = try reader.payloadData(maxSize: maxPayloadSize ?? TDFArchiveReader.defaultPayloadMaxSize) + let payload = try reader.payloadData(maxSize: maxPayloadSize) return TDFContainer(manifest: manifest, payload: payload) } } diff --git a/OpenTDFKit/TDF/TDFCBORFormat.swift b/OpenTDFKit/TDF/TDFCBORFormat.swift index bd12e43..69c126f 100644 --- a/OpenTDFKit/TDF/TDFCBORFormat.swift +++ b/OpenTDFKit/TDF/TDFCBORFormat.swift @@ -614,15 +614,28 @@ extension TDFCBOREnvelope { maxDepth: Int = 32, maxItems: Int = 100_000, ) throws { - enum Frame { + enum FrameKind { case definite(remaining: Int) case indefiniteContainer case indefiniteString(major: UInt8) } + struct Frame { + let kind: FrameKind + let depth: Int + } + var offset = 0 var itemCount = 0 - var stack: [Frame] = [.definite(remaining: 1)] + var stack: [Frame] = [Frame(kind: .definite(remaining: 1), depth: 0)] + + func pushChild(_ kind: FrameKind, parentDepth: Int) throws { + let childDepth = parentDepth + 1 + guard childDepth <= maxDepth else { + throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") + } + stack.append(Frame(kind: kind, depth: childDepth)) + } func readArgument(ai: UInt8) throws -> UInt64 { switch ai { @@ -672,22 +685,28 @@ extension TDFCBOREnvelope { throw TDFCBORError.cborDecodingFailed("Truncated CBOR input") } - switch frame { + let currentDepth = frame.depth + + switch frame.kind { case let .definite(remaining): if remaining > 1 { - stack.append(.definite(remaining: remaining - 1)) + stack.append(Frame(kind: .definite(remaining: remaining - 1), depth: currentDepth)) } case .indefiniteContainer: if bytes[offset] == 0xFF { offset += 1 continue } - stack.append(.indefiniteContainer) + stack.append(Frame(kind: .indefiniteContainer, depth: currentDepth)) case let .indefiniteString(expectedMajor): if bytes[offset] == 0xFF { offset += 1 continue } + itemCount += 1 + guard itemCount <= maxItems else { + throw TDFCBORError.cborDecodingFailed("CBOR item count exceeds safety limit") + } let initial = bytes[offset] offset += 1 let major = initial >> 5 @@ -700,7 +719,7 @@ extension TDFCBOREnvelope { throw TDFCBORError.cborDecodingFailed("CBOR string chunk length exceeds remaining input") } offset += Int(chunkLen) - stack.append(.indefiniteString(major: expectedMajor)) + stack.append(Frame(kind: .indefiniteString(major: expectedMajor), depth: currentDepth)) continue } @@ -722,10 +741,7 @@ extension TDFCBOREnvelope { _ = try readArgument(ai: ai) case 2, 3: if ai == 31 { - guard stack.count < maxDepth else { - throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") - } - stack.append(.indefiniteString(major: major)) + try pushChild(.indefiniteString(major: major), parentDepth: currentDepth) } else { let length = try readArgument(ai: ai) guard length <= UInt64(bytes.count - offset) else { @@ -735,38 +751,26 @@ extension TDFCBOREnvelope { } case 4: if ai == 31 { - guard stack.count < maxDepth else { - throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") - } - stack.append(.indefiniteContainer) + try pushChild(.indefiniteContainer, parentDepth: currentDepth) } else { let count = try readArgument(ai: ai) guard count <= UInt64(bytes.count - offset) else { throw TDFCBORError.cborDecodingFailed("CBOR array length \(count) exceeds remaining input") } if count > 0 { - guard stack.count < maxDepth else { - throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") - } - stack.append(.definite(remaining: Int(count))) + try pushChild(.definite(remaining: Int(count)), parentDepth: currentDepth) } } case 5: if ai == 31 { - guard stack.count < maxDepth else { - throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") - } - stack.append(.indefiniteContainer) + try pushChild(.indefiniteContainer, parentDepth: currentDepth) } else { let pairs = try readArgument(ai: ai) guard pairs <= UInt64((bytes.count - offset) / 2) else { throw TDFCBORError.cborDecodingFailed("CBOR map length \(pairs) exceeds remaining input") } if pairs > 0 { - guard stack.count < maxDepth else { - throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") - } - stack.append(.definite(remaining: Int(pairs) * 2)) + try pushChild(.definite(remaining: Int(pairs) * 2), parentDepth: currentDepth) } } case 6: @@ -774,10 +778,7 @@ extension TDFCBOREnvelope { throw TDFCBORError.cborDecodingFailed("Invalid indefinite length for CBOR tag") } _ = try readArgument(ai: ai) - guard stack.count < maxDepth else { - throw TDFCBORError.cborDecodingFailed("CBOR nesting depth exceeds limit") - } - stack.append(.definite(remaining: 1)) + try pushChild(.definite(remaining: 1), parentDepth: currentDepth) case 7: guard ai != 31 else { throw TDFCBORError.cborDecodingFailed("Unexpected CBOR break byte") @@ -800,10 +801,11 @@ extension TDFCBOREnvelope { throw TDFCBORError.invalidMagicBytes } - // Skip self-describe tag, validate CBOR structure iteratively, then decode + // Skip self-describe tag, validate CBOR structure iteratively, then decode with bounded depth let cborBytes = Array(data.dropFirst(3)) - try validateCBORStructure(cborBytes) - guard let decoded = try? CBOR.decode(cborBytes) else { + let maxCBORDepth = 32 + try validateCBORStructure(cborBytes, maxDepth: maxCBORDepth) + guard let decoded = try? CBOR.decode(cborBytes, options: CBOROptions(maximumDepth: maxCBORDepth)) else { throw TDFCBORError.cborDecodingFailed("Failed to decode CBOR") } diff --git a/OpenTDFKit/TDF/TDFFormatDetector.swift b/OpenTDFKit/TDF/TDFFormatDetector.swift index 3e4a4b9..a0448a9 100644 --- a/OpenTDFKit/TDF/TDFFormatDetector.swift +++ b/OpenTDFKit/TDF/TDFFormatDetector.swift @@ -117,12 +117,11 @@ public enum TDFFormatDetector { return .nano } - // Speculative JSON detection: bound file size before reading & parsing + // Speculative JSON detection: bound bytes read directly to prevent TOCTOU races if headerBytes.first == jsonStart { - guard let size = try? handle.seekToEnd(), - size <= UInt64(maxJSONDetectionSize), - (try? handle.seek(toOffset: 0)) != nil, - let data = try? handle.readToEnd() + guard (try? handle.seek(toOffset: 0)) != nil, + let data = try? handle.read(upToCount: maxJSONDetectionSize + 1), + data.count <= maxJSONDetectionSize else { return nil } diff --git a/OpenTDFKit/TDF/TDFProcessor.swift b/OpenTDFKit/TDF/TDFProcessor.swift index 5c9e87a..33d4809 100644 --- a/OpenTDFKit/TDF/TDFProcessor.swift +++ b/OpenTDFKit/TDF/TDFProcessor.swift @@ -566,7 +566,12 @@ public struct TDFDecryptor { encryptionInformation: container.manifest.encryptionInformation, privateKeyPEM: privateKeyPEM, ) - try decrypt(container: container, symmetricKey: symmetricKey).write(to: outputURL) + try decryptEncryptionInfo( + container.manifest.encryptionInformation, + payload: container.payload, + symmetricKey: symmetricKey, + policyBindingAlreadyVerified: true, + ).write(to: outputURL) } public func decryptFileMultiSegment( @@ -584,7 +589,81 @@ public struct TDFDecryptor { encryptionInformation: container.manifest.encryptionInformation, privateKeyPEM: privateKeyPEM, ) - return try decrypt(container: container, symmetricKey: symmetricKey) + return try decryptEncryptionInfo( + container.manifest.encryptionInformation, + payload: container.payload, + symmetricKey: symmetricKey, + policyBindingAlreadyVerified: true, + ) + } + + /// Decrypts a Standard TDF (single- or multi-split) using unwrapped per-split key shares. + /// Verifies each split's `policyBinding` against its matching key access object(s) in the + /// manifest, requires every manifest split to be satisfied, XOR-combines the verified shares + /// into the DEK, and verifies payload integrity before returning plaintext. + public func decrypt(container: TDFContainer, keyShares: [TDFKeyShare]) throws -> Data { + let encryptionInfo = container.manifest.encryptionInformation + let keyAccess = encryptionInfo.keyAccess + guard !keyAccess.isEmpty else { + throw TDFDecryptError.policyBindingFailed + } + + let policyBase64 = encryptionInfo.policy + var kaBySplit: [String: [TDFKeyAccessObject]] = [:] + var splitOrder: [String] = [] + for kao in keyAccess { + let sid = kao.sid ?? "" + if kaBySplit[sid] == nil { + splitOrder.append(sid) + } + kaBySplit[sid, default: []].append(kao) + } + + var verifiedShares: [String: Data] = [:] + defer { + for sid in verifiedShares.keys { + verifiedShares[sid]?.secureZero() + } + } + + for share in keyShares { + let sid = share.sid ?? "" + guard verifiedShares[sid] == nil, let candidates = kaBySplit[sid] else { + continue + } + let bindingValid = candidates.contains { kao in + TDFCrypto.verifyPolicyBinding( + kao.policyBinding, + policyBase64: policyBase64, + symmetricKey: share.key, + ) + } + guard bindingValid else { + throw TDFDecryptError.policyBindingFailed + } + verifiedShares[sid] = TDFCrypto.data(from: share.key) + } + + guard verifiedShares.count == splitOrder.count else { + throw TDFDecryptError.policyBindingFailed + } + + var dek = try Self.combineKeyShares(splitOrder.map { sid in + (sid: sid, unwrap: { + guard let share = verifiedShares[sid] else { + throw TDFDecryptError.missingKeyAccess + } + return share + }) + }) + defer { dek.secureZero() } + + return try decryptEncryptionInfo( + encryptionInfo, + payload: container.payload, + symmetricKey: SymmetricKey(data: dek), + policyBindingAlreadyVerified: true, + ) } /// Payload algorithms `decrypt` accepts. AES-128-GCM is only written by @@ -699,6 +778,7 @@ public struct TDFDecryptor { _ encryptionInformation: TDFEncryptionInformation, payload: Data, symmetricKey: SymmetricKey, + policyBindingAlreadyVerified: Bool = false, ) throws -> Data { let expectedBits = try Self.expectedKeyBitCount(for: encryptionInformation.method.algorithm) guard symmetricKey.bitCount == expectedBits else { @@ -713,10 +793,16 @@ public struct TDFDecryptor { // Decrypt and verify all segments + root signature before verifying policy binding and returning var plaintext = try decryptSegments(payload: payload, integrity: integrity, symmetricKey: symmetricKey) - // Verify policy binding for single-split manifests (in multi-split manifests each KAO binds its own share) - let keyAccess = encryptionInformation.keyAccess - let distinctSplits = Set(keyAccess.map { $0.sid ?? "" }) - if !keyAccess.isEmpty, distinctSplits.count <= 1 { + if !policyBindingAlreadyVerified { + // Bare-DEK decryption must fail closed if KAOs are absent or multi-split + // (in multi-split manifests each KAO binds its own share, so callers must + // use `decrypt(container:privateKeyPEM:)` or `decrypt(container:keyShares:)`). + let keyAccess = encryptionInformation.keyAccess + let distinctSplits = Set(keyAccess.map { $0.sid ?? "" }) + guard !keyAccess.isEmpty, distinctSplits.count == 1 else { + plaintext.secureZero() + throw TDFDecryptError.policyBindingFailed + } let bindingValid = keyAccess.contains { kao in TDFCrypto.verifyPolicyBinding( kao.policyBinding, diff --git a/OpenTDFKitCLI/Commands.swift b/OpenTDFKitCLI/Commands.swift index 62bc515..636f51a 100644 --- a/OpenTDFKitCLI/Commands.swift +++ b/OpenTDFKitCLI/Commands.swift @@ -283,10 +283,7 @@ enum Commands { throw DecryptError.missingWrappedKey } - let dek = try TDFDecryptor.combineKeyShares(keyShares.map { share in - (sid: share.sid, unwrap: { TDFCrypto.data(from: share.key) }) - }) - return try decryptor.decrypt(container: container, symmetricKey: SymmetricKey(data: dek)) + return try decryptor.decrypt(container: container, keyShares: keyShares) } /// Acquire an OAuth access token via client_credentials. @@ -1086,11 +1083,11 @@ extension Commands { ) print("✓ Key unwrapped successfully") - // Create decryptor with the unwrapped key + // Create decryptor with the unwrapped key (verifies header policy binding) let cipher = header.payloadSignatureConfig.payloadCipher ?? .aes256GCM128 - let decryptor = NanoTDFCollectionDecryptor.withUnwrappedKey( + let decryptor = try NanoTDFCollectionDecryptor.withUnwrappedKey( + header: header, symmetricKey: payloadKey, - cipher: cipher, ) // Parse and decrypt all items diff --git a/OpenTDFKitTests/SecurityAuditRegressionTests.swift b/OpenTDFKitTests/SecurityAuditRegressionTests.swift index 52ac589..ce99a38 100644 --- a/OpenTDFKitTests/SecurityAuditRegressionTests.swift +++ b/OpenTDFKitTests/SecurityAuditRegressionTests.swift @@ -141,6 +141,24 @@ final class SecurityAuditRegressionTests: XCTestCase { let decryptor = try await NanoTDFCollectionDecryptor.withKeyStore(header: header, keyStore: keyStore) let decrypted = try await decryptor.decryptItem(item) XCTAssertEqual(decrypted, Data("hello".utf8)) + + // Client-side withUnwrappedKey(header:symmetricKey:) verifies policy binding and rejects tampering + let clientDecryptor = try NanoTDFCollectionDecryptor.withUnwrappedKey(header: header, symmetricKey: symKey) + let clientDecrypted = try await clientDecryptor.decryptItem(item) + XCTAssertEqual(clientDecrypted, Data("hello".utf8)) + + var tamperedPolicy = header.policy + tamperedPolicy.body = EmbeddedPolicyBody(body: Data("tampered-policy".utf8), keyAccess: tamperedPolicy.body?.keyAccess) + let tamperedHeader = Header( + payloadKeyAccess: header.payloadKeyAccess, + policyBindingConfig: header.policyBindingConfig, + payloadSignatureConfig: header.payloadSignatureConfig, + policy: tamperedPolicy, + ephemeralPublicKey: header.ephemeralPublicKey, + ) + XCTAssertThrowsError(try NanoTDFCollectionDecryptor.withUnwrappedKey(header: tamperedHeader, symmetricKey: symKey)) { error in + XCTAssertEqual(error as? NanoTDFError, .invalidPolicyBinding) + } } // MARK: - #4: Data Slices (startIndex > 0) & Offset Safety @@ -377,13 +395,16 @@ final class SecurityAuditRegressionTests: XCTestCase { // IPv6 zone IDs "https://[fe80::1%25en0]/kas", "http://[::1%25lo0]/kas", - // Non-canonical IPv4 (integer, hex, octal, shorthand) + // Non-canonical IPv4 (integer, hex, octal, shorthand, trailing dot) "https://2130706433/kas", "https://2852039166/kas", "https://0x7f000001/kas", "https://0177.0.0.1/kas", "https://127.1/kas", "https://10.1/kas", + "https://169.254.169.254./kas", + "https://10.0.0.1./kas", + "https://127.0.0.1./kas", // Missing CIDRs "https://0.1.2.3/kas", "https://100.64.0.1/kas", @@ -393,6 +414,8 @@ final class SecurityAuditRegressionTests: XCTestCase { "https://255.255.255.255/kas", "https://[::ffff:127.0.0.1]/kas", "https://[::ffff:8.8.8.8]/kas", + "https://[::7f00:1]/kas", + "https://[::169.254.169.254]/kas", "https://[64:ff9b::10.0.0.1]/kas", "https://[ff02::1]/kas", // Userinfo @@ -427,6 +450,37 @@ final class SecurityAuditRegressionTests: XCTestCase { XCTFail("Unexpected error: \(error)") } + // Redirects (302) are refused rather than followed + MockURLProtocol.handler = { req in + let resp = HTTPURLResponse( + url: req.url!, + statusCode: 302, + httpVersion: nil, + headerFields: ["Location": "https://169.254.169.254/latest/meta-data/"], + )! + return (resp, Data()) + } + do { + _ = try await fetchWellKnown(platformURL: "https://platform.example.com", urlSession: MockURLProtocol.makeSession()) + XCTFail("Expected httpError(302) without following redirect") + } catch let KASDiscoveryError.httpError(code, _) { + XCTAssertEqual(code, 302) + } catch { + XCTFail("Unexpected error: \(error)") + } + + // Oversized well-known response (> 1 MiB) rejected + MockURLProtocol.handler = { req in + let resp = HTTPURLResponse(url: req.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return (resp, Data(repeating: 0x20, count: BoundedHTTPClient.defaultWellKnownMaxBytes + 1024)) + } + do { + _ = try await fetchWellKnown(platformURL: "https://platform.example.com", urlSession: MockURLProtocol.makeSession()) + XCTFail("Expected invalidResponse on oversized well-known response") + } catch KASDiscoveryError.invalidResponse {} catch { + XCTFail("Unexpected error: \(error)") + } + // Oversized transport response rejected MockURLProtocol.handler = { req in let resp = HTTPURLResponse(url: req.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! @@ -439,6 +493,27 @@ final class SecurityAuditRegressionTests: XCTestCase { } catch KASRewrapError.invalidResponse {} catch { XCTFail("Unexpected error: \(error)") } + + // Pre-cancelled task must never hang BoundedHTTPClient.send + MockURLProtocol.handler = { req in + let resp = HTTPURLResponse(url: req.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! + return (resp, Data("ok".utf8)) + } + let cancelledTask = Task { + try await withTaskCancellationHandler { + try await BoundedHTTPClient.send( + URLRequest(url: URL(string: "https://kas.example.com/cancelled")!), + on: MockURLProtocol.makeSession(), + maxBytes: 1024, + ) + } onCancel: {} + } + cancelledTask.cancel() + do { + _ = try await cancelledTask.value + } catch { + // Expected cancellation / URLError.cancelled without hanging + } } func testKASServiceRewrapKeyRejectsSSRFURL() async { @@ -475,6 +550,35 @@ final class SecurityAuditRegressionTests: XCTestCase { ) let sealed = try AES.GCM.seal(Data(repeating: 0x42, count: 16), using: primaryKey) let encryptedKey = sealed.combined! + let policyBody = Data(#"{"uuid":"p1"}"#.utf8) + let validBinding = try CryptoHelper().createGMACBinding(policyBody: policyBody, symmetricKey: primaryKey) + let invalidBinding = Data(repeating: 0xFF, count: validBinding.count) + + // Malformed request must NOT burn the one-time key + do { + _ = try await kasService.processKeyAccessWithKeyIdentifier( + ephemeralPublicKey: Data(), + encryptedKey: Data(), + kasPublicKey: kasPair.publicKey, + policyBody: policyBody, + policyBinding: validBinding, + ) + XCTFail("Expected malformed request to fail") + } catch {} + + // Tampered policy binding must fail with accessDenied and NOT burn the key + do { + _ = try await kasService.processKeyAccessWithKeyIdentifier( + ephemeralPublicKey: clientPriv.publicKey.compressedRepresentation, + encryptedKey: encryptedKey, + kasPublicKey: kasPair.publicKey, + policyBody: policyBody, + policyBinding: invalidBinding, + ) + XCTFail("Expected tampered binding to fail") + } catch KASServiceError.accessDenied {} catch { + XCTFail("Expected accessDenied, got \(error)") + } // Launch 8 concurrent rewraps against the same one-time key; exactly 1 must succeed. var successes = 0 @@ -487,6 +591,8 @@ final class SecurityAuditRegressionTests: XCTestCase { ephemeralPublicKey: clientPriv.publicKey.compressedRepresentation, encryptedKey: encryptedKey, kasPublicKey: kasPair.publicKey, + policyBody: policyBody, + policyBinding: validBinding, ) return .success(res) } catch { @@ -509,8 +615,33 @@ final class SecurityAuditRegressionTests: XCTestCase { ephemeralPublicKey: clientPriv.publicKey.compressedRepresentation, encryptedKey: encryptedKey, kasPublicKey: kasPair.publicKey, + policyBody: policyBody, + policyBinding: validBinding, ) XCTAssertEqual(keyIDs.first, secondID) + + // Verify processKeyAccess(header:encryptedKey:) works with a parsed v12 header (empty kasPublicKey) + await keyStore.store(keyPair: kasPair) + let kasPubKeyObj = try P256.KeyAgreement.PublicKey(compressedRepresentation: kasPair.publicKey) + let kasRL = try XCTUnwrap(ResourceLocator(protocolEnum: .https, body: "kas.example.com")) + let kasMeta = try KasMetadata( + resourceLocator: kasRL, + publicKey: kasPubKeyObj, + curve: .secp256r1, + ) + var policy = Policy( + type: .embeddedPlaintext, + body: EmbeddedPolicyBody(body: Data("v12-policy".utf8), keyAccess: nil), + remote: nil, + binding: nil, + ) + let nano = try await createNanoTDF(kas: kasMeta, policy: &policy, plaintext: Data("secret".utf8)) + let parsedHeader = try BinaryParser(data: nano.toData()).parseHeader() + XCTAssertTrue(parsedHeader.payloadKeyAccess.kasPublicKey.isEmpty) + let headerKey = try await keyStore.derivePayloadSymmetricKey(header: parsedHeader) + let headerEncKey = try AES.GCM.seal(Data(repeating: 0x33, count: 16), using: headerKey).combined! + let rewrapped = try await kasService.processKeyAccess(header: parsedHeader, encryptedKey: headerEncKey) + XCTAssertFalse(rewrapped.isEmpty) } // MARK: - #13, #14, #31: TDF Policy Binding, Algorithm/Key Size & JSON/CBOR Hardening @@ -530,6 +661,47 @@ final class SecurityAuditRegressionTests: XCTestCase { XCTAssertEqual(error as? TDFDecryptError, .policyBindingFailed) } + // Clearing keyAccess after tampering policy MUST NOT bypass policy binding + var emptyKAManifest = tamperedManifest + emptyKAManifest.encryptionInformation.keyAccess = [] + let emptyKAContainer = TDFContainer(manifest: emptyKAManifest, payload: result.container.payload) + XCTAssertThrowsError(try TDFDecryptor().decrypt(container: emptyKAContainer, symmetricKey: result.symmetricKey)) { error in + XCTAssertEqual(error as? TDFDecryptError, .policyBindingFailed) + } + + // Injecting a second KAO with a different sid MUST NOT bypass policy binding on bare-DEK decrypt + var fakeSplitManifest = tamperedManifest + var kao1 = fakeSplitManifest.encryptionInformation.keyAccess[0] + kao1.sid = "split-a" + var kao2 = kao1 + kao2.sid = "split-b" + fakeSplitManifest.encryptionInformation.keyAccess = [kao1, kao2] + let fakeSplitContainer = TDFContainer(manifest: fakeSplitManifest, payload: result.container.payload) + XCTAssertThrowsError(try TDFDecryptor().decrypt(container: fakeSplitContainer, symmetricKey: result.symmetricKey)) { error in + XCTAssertEqual(error as? TDFDecryptError, .policyBindingFailed) + } + + // Legitimate multi-split decryption via decrypt(container:keyShares:) verifies every share's binding + let share1Data = Data(repeating: 0xAA, count: 32) + let dekData = TDFCrypto.data(from: result.symmetricKey) + let share2Data = Data(zip(dekData, share1Data).map { $0 ^ $1 }) + let share1Key = SymmetricKey(data: share1Data) + let share2Key = SymmetricKey(data: share2Data) + var realSplitManifest = result.container.manifest + var splitKAO1 = realSplitManifest.encryptionInformation.keyAccess[0] + splitKAO1.sid = "s1" + splitKAO1.policyBinding = TDFCrypto.policyBinding(policy: policy.json, symmetricKey: share1Key) + var splitKAO2 = splitKAO1 + splitKAO2.sid = "s2" + splitKAO2.policyBinding = TDFCrypto.policyBinding(policy: policy.json, symmetricKey: share2Key) + realSplitManifest.encryptionInformation.keyAccess = [splitKAO1, splitKAO2] + let realSplitContainer = TDFContainer(manifest: realSplitManifest, payload: result.container.payload) + let decryptedMulti = try TDFDecryptor().decrypt( + container: realSplitContainer, + keyShares: [TDFKeyShare(sid: "s1", key: share1Key), TDFKeyShare(sid: "s2", key: share2Key)], + ) + XCTAssertEqual(decryptedMulti, Data("hello".utf8)) + // Mismatched key size (128-bit key with AES-256-GCM manifest) -> keySizeMismatch let key128 = SymmetricKey(size: .bits128) XCTAssertThrowsError(try TDFDecryptor().decrypt(container: result.container, symmetricKey: key128)) { error in @@ -557,8 +729,12 @@ final class SecurityAuditRegressionTests: XCTestCase { payload: jsonRes.container.envelope.payload, ) let badJSONContainer = TDFJSONContainer(envelope: badJSONEnv, payloadData: jsonRes.container.payloadData) - XCTAssertThrowsError(try TDFJSONDecryptor().decrypt(container: badJSONContainer, symmetricKey: jsonRes.symmetricKey)) - XCTAssertThrowsError(try TDFJSONDecryptor().decrypt(container: badJSONContainer, privateKeyPEM: ecKey.pemRepresentation)) + XCTAssertThrowsError(try TDFJSONDecryptor().decrypt(container: badJSONContainer, symmetricKey: jsonRes.symmetricKey)) { error in + XCTAssertEqual(error as? TDFDecryptError, .policyBindingFailed) + } + XCTAssertThrowsError(try TDFJSONDecryptor().decrypt(container: badJSONContainer, privateKeyPEM: ecKey.pemRepresentation)) { error in + XCTAssertEqual(error as? TDFDecryptError, .policyBindingFailed) + } // TDF-JSON: payload.length mismatch rejected on decodePayloadValue var mismatchedPayload = jsonRes.container.envelope.payload @@ -569,7 +745,11 @@ final class SecurityAuditRegressionTests: XCTestCase { manifest: jsonRes.container.manifest, payload: mismatchedPayload, ) - XCTAssertThrowsError(try mismatchedEnv.decodePayloadValue()) + XCTAssertThrowsError(try mismatchedEnv.decodePayloadValue()) { error in + guard case TDFJSONError.payloadDecodeError = error else { + return XCTFail("Expected payloadDecodeError, got \(error)") + } + } // TDF-CBOR: tamper integrity root signature let cborRes = try TDFCBORBuilder() @@ -584,7 +764,9 @@ final class SecurityAuditRegressionTests: XCTestCase { manifest: TDFCBORManifest(encryptionInformation: badCBOREncInfo), payload: cborRes.container.envelope.payload, ) - XCTAssertThrowsError(try TDFCBORDecryptor().decrypt(container: TDFCBORContainer(envelope: badCBOREnv), symmetricKey: cborRes.symmetricKey)) + XCTAssertThrowsError(try TDFCBORDecryptor().decrypt(container: TDFCBORContainer(envelope: badCBOREnv), symmetricKey: cborRes.symmetricKey)) { error in + XCTAssertEqual(error as? TDFDecryptError, .integrityCheckFailed) + } // TDF-CBOR: reject multi-split manifest var splitEncInfo = cborRes.container.encryptionInformation @@ -594,7 +776,11 @@ final class SecurityAuditRegressionTests: XCTestCase { kao2.sid = "split-2" splitEncInfo.keyAccess = [kao1, kao2] let splitEnv = TDFCBOREnvelope(manifest: TDFCBORManifest(encryptionInformation: splitEncInfo), payload: cborRes.container.envelope.payload) - XCTAssertThrowsError(try TDFCBORDecryptor().decrypt(container: TDFCBORContainer(envelope: splitEnv), privateKeyPEM: ecKey.pemRepresentation)) + XCTAssertThrowsError(try TDFCBORDecryptor().decrypt(container: TDFCBORContainer(envelope: splitEnv), privateKeyPEM: ecKey.pemRepresentation)) { error in + guard case TDFCBORError.decryptionFailed = error else { + return XCTFail("Expected decryptionFailed, got \(error)") + } + } } func testECWrapUnwrapSupportsP384AndP521() throws { @@ -646,6 +832,38 @@ final class SecurityAuditRegressionTests: XCTestCase { try inHandle.close() try encHandle.close() + // Missing rootSignature on multi-segment payload must be rejected + let readEncMissingRoot = try FileHandle(forReadingFrom: encURL) + let outHandleMissingRoot = try FileHandle(forWritingTo: outURL) + XCTAssertThrowsError(try StreamingTDFCrypto.decryptPayloadStreamingMultiSegment( + inputHandle: readEncMissingRoot, + outputHandle: outHandleMissingRoot, + segments: encResult.segments, + symmetricKey: key, + rootSignature: nil, + )) + try readEncMissingRoot.close() + try outHandleMissingRoot.close() + + // Reordered segments + matching swapped payload bytes must be rejected by rootSignature + let encBytes = try Data(contentsOf: encURL) + let seg0Len = Int(encResult.segments[0].encryptedSize) + let swappedBytes = encBytes.dropFirst(seg0Len) + encBytes.prefix(seg0Len) + let swappedURL = FileManager.default.temporaryDirectory.appendingPathComponent("stream-swap-\(UUID().uuidString)") + try Data(swappedBytes).write(to: swappedURL) + defer { try? FileManager.default.removeItem(at: swappedURL) } + let readSwapped = try FileHandle(forReadingFrom: swappedURL) + let outHandleSwapped = try FileHandle(forWritingTo: outURL) + XCTAssertThrowsError(try StreamingTDFCrypto.decryptPayloadStreamingMultiSegment( + inputHandle: readSwapped, + outputHandle: outHandleSwapped, + segments: [encResult.segments[1], encResult.segments[0]], + symmetricKey: key, + rootSignature: encResult.rootSignature, + )) + try readSwapped.close() + try outHandleSwapped.close() + // Corrupt segment 1's expected hash while leaving segment 0 valid var tamperedSegments = encResult.segments tamperedSegments[1] = StreamingTDFCrypto.EncryptedSegment( @@ -662,6 +880,7 @@ final class SecurityAuditRegressionTests: XCTestCase { outputHandle: outHandle, segments: tamperedSegments, symmetricKey: key, + rootSignature: encResult.rootSignature, )) try readEnc.close() try outHandle.close() @@ -669,11 +888,47 @@ final class SecurityAuditRegressionTests: XCTestCase { // Output file MUST remain empty (no unverified segment 0 plaintext leaked) let written = try Data(contentsOf: outURL) XCTAssertTrue(written.isEmpty, "No plaintext should be written to outputHandle when a later segment fails") + + // Valid multi-segment round-trip with rootSignature succeeds + let readValid = try FileHandle(forReadingFrom: encURL) + let outValid = try FileHandle(forWritingTo: outURL) + try StreamingTDFCrypto.decryptPayloadStreamingMultiSegment( + inputHandle: readValid, + outputHandle: outValid, + segments: encResult.segments, + symmetricKey: key, + rootSignature: encResult.rootSignature, + ) + try readValid.close() + try outValid.close() + XCTAssertEqual(try Data(contentsOf: outURL), Data("segment-one-data|segment-two-data".utf8)) + + // HS256 segment hash verification succeeds when valid and rejects GMAC-tag substitution + let seg0Bytes = Data(encBytes.prefix(seg0Len)) + let seg1Bytes = Data(encBytes.dropFirst(seg0Len)) + let hs0 = Data(HMAC.authenticationCode(for: seg0Bytes, using: key)) + let hs1 = Data(HMAC.authenticationCode(for: seg1Bytes, using: key)) + let hsRoot = Data(HMAC.authenticationCode(for: hs0 + hs1, using: key)).base64EncodedString() + let hsSegments = [ + StreamingTDFCrypto.EncryptedSegment(segmentIndex: 0, plaintextSize: 16, encryptedSize: Int64(seg0Bytes.count), hash: hs0.base64EncodedString()), + StreamingTDFCrypto.EncryptedSegment(segmentIndex: 1, plaintextSize: 17, encryptedSize: Int64(seg1Bytes.count), hash: hs1.base64EncodedString()), + ] + let hsDecrypted = try StreamingTDFCrypto.decryptPayloadMultiSegmentFromMemory( + encryptedPayload: encBytes, + segments: hsSegments, + symmetricKey: key, + rootSignature: hsRoot, + segmentHashAlg: "HS256", + ) + XCTAssertEqual(hsDecrypted, Data("segment-one-data|segment-two-data".utf8)) } - // MARK: - #16: ZIP Archive Caps + // MARK: - #16: ZIP Archive Caps & TDFLoader Default vs Explicit nil func testArchiveReaderWritePayloadEnforcesMaxSize() throws { + XCTAssertEqual(TDFLoader().maxPayloadSize, TDFArchiveReader.defaultPayloadMaxSize) + XCTAssertNil(TDFLoader(maxPayloadSize: nil).maxPayloadSize) + let manifest = TDFManifest( schemaVersion: "4.3.0", payload: TDFPayloadDescriptor(type: .reference, url: "0.payload", protocolValue: .zip, isEncrypted: true), @@ -706,15 +961,46 @@ final class SecurityAuditRegressionTests: XCTestCase { XCTAssertGreaterThan(cborSlice.startIndex, 0) XCTAssertTrue(TDFCBOREnvelope.hasMagicBytes(cborSlice)) - // #17: Deeply nested CBOR array (depth 100) rejected cleanly without stack overflow - var deeplyNested = Data(TDF_CBOR_MAGIC) - deeplyNested.append(contentsOf: [UInt8](repeating: 0x81, count: 100)) - deeplyNested.append(0x00) - XCTAssertThrowsError(try TDFCBOREnvelope.fromCBORData(deeplyNested)) + // #17: Deeply nested single-element CBOR array (depth 100 and 10_000) inside a map root + // must trigger the depth limit specifically (not "Expected CBOR map at root"). + for depth in [100, 10000] { + var deeplyNested = Data(TDF_CBOR_MAGIC) + deeplyNested.append(0xA1) // 1-entry map + deeplyNested.append(0x18) + deeplyNested.append(0x63) // key 99 + deeplyNested.append(contentsOf: [UInt8](repeating: 0x81, count: depth)) + deeplyNested.append(0x00) + XCTAssertThrowsError(try TDFCBOREnvelope.fromCBORData(deeplyNested)) { error in + guard case let TDFCBORError.cborDecodingFailed(msg) = error else { + return XCTFail("Expected cborDecodingFailed, got \(error)") + } + XCTAssertTrue(msg.contains("nesting depth"), "Expected depth-limit failure, got: \(msg)") + } + } + + // #17: Indefinite byte-string and text-string chunk amplification (> maxItems) rejected + for (indefHeader, emptyChunk): (UInt8, UInt8) in [(0x5F, 0x40), (0x7F, 0x60)] { + var chunkBomb = Data(TDF_CBOR_MAGIC) + chunkBomb.append(0xA1) + chunkBomb.append(0x01) + chunkBomb.append(indefHeader) + chunkBomb.append(contentsOf: [UInt8](repeating: emptyChunk, count: 105_000)) + chunkBomb.append(0xFF) + XCTAssertThrowsError(try TDFCBOREnvelope.fromCBORData(chunkBomb)) { error in + guard case let TDFCBORError.cborDecodingFailed(msg) = error else { + return XCTFail("Expected cborDecodingFailed, got \(error)") + } + XCTAssertTrue(msg.contains("item count"), "Expected item-count failure, got: \(msg)") + } + } // #17: Crafted huge byte string length (0x5B + UInt64.max) rejected before SwiftCBOR allocates let hugeBstr = Data(TDF_CBOR_MAGIC + [0x5B, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) - XCTAssertThrowsError(try TDFCBOREnvelope.fromCBORData(hugeBstr)) + XCTAssertThrowsError(try TDFCBOREnvelope.fromCBORData(hugeBstr)) { error in + guard case TDFCBORError.cborDecodingFailed = error else { + return XCTFail("Expected cborDecodingFailed, got \(error)") + } + } // #29: PEM ephemeralPublicKey, sid, encryptedMetadata preserved; nil encryptedSegmentSizeDefault stays nil let pem = P256.KeyAgreement.PrivateKey().publicKey.pemRepresentation From 51bcd61ad53f0a9b841d4d7f2373de6bd67e6255 Mon Sep 17 00:00:00 2001 From: Paul Flynn Date: Sun, 22 Nov 2026 19:59:55 -0500 Subject: [PATCH 3/3] fix: address Round 2 PR #70 review findings (Codex, Claude, Grok) - StreamingTDFCrypto: require rootSignature for every payload (including 1-segment, blocking truncation-to-1-segment bypasses), re-verify each Pass-2 segment signature against Pass 1 with length guards before writing, and ensure decryptPayloadMultiSegmentFromMemory zeroes plaintext on all error exits. - TDFProcessor: skip invalid replica shares in decrypt(container:keyShares:) so another valid replica for the same split can succeed; document single-split vs keyShares usage across TDFProcessor, KASRewrapClient, and TDFKAS. - KASService: peek-validate-then-pop in processKeyAccessWithKeyIdentifier so malformed requests neither burn one-time keys nor create transient keyNotFound windows for concurrent valid callers. - KASDiscovery: guard BoundedHTTPClient chunk-size check against data.count > maxBytes underflow and block 6to4 (2002::/16) and Teredo (2001:0000::/32) IPv6 prefixes. - NanoTDF & Tests: add NanoTDFError.payloadLengthMismatch for Payload.serializedData() and expand regression tests for 1-segment nil root, bad replica share, 6to4/Teredo, deterministic cancellation, and payload length mismatch. --- OpenTDFKit/KASDiscovery.swift | 10 ++- OpenTDFKit/KASRewrapClient.swift | 8 +- OpenTDFKit/KASService.swift | 33 ++++---- OpenTDFKit/NanoTDF.swift | 5 +- OpenTDFKit/TDF/StreamingTDFCrypto.swift | 76 ++++++++++++------- OpenTDFKit/TDF/TDFKAS.swift | 4 +- OpenTDFKit/TDF/TDFProcessor.swift | 9 ++- .../SecurityAuditRegressionTests.swift | 61 ++++++++++++--- OpenTDFKitTests/StreamingTDFCryptoTests.swift | 11 +++ 9 files changed, 150 insertions(+), 67 deletions(-) diff --git a/OpenTDFKit/KASDiscovery.swift b/OpenTDFKit/KASDiscovery.swift index 0979a7f..be441fc 100644 --- a/OpenTDFKit/KASDiscovery.swift +++ b/OpenTDFKit/KASDiscovery.swift @@ -380,6 +380,14 @@ private func isBlockedIP(_ ip: IPLiteral) -> Bool { return true } } + // 2002::/16 (6to4, RFC 3056 — embeds IPv4 in bytes 2..<6) + if b[0] == 0x20, b[1] == 0x02 { + return true + } + // 2001:0000::/32 (Teredo, RFC 4380 — embeds IPv4) + if b[0] == 0x20, b[1] == 0x01, b[2] == 0x00, b[3] == 0x00 { + return true + } // ff00::/8 multicast if b[0] == 0xFF { return true @@ -628,7 +636,7 @@ enum BoundedHTTPClient { if case .delivered = state { return true } - if buffer.count > maxBytes - data.count { + if maxBytes < 0 || data.count > maxBytes || buffer.count > maxBytes - data.count { overflowed = true buffer.removeAll(keepingCapacity: false) return true diff --git a/OpenTDFKit/KASRewrapClient.swift b/OpenTDFKit/KASRewrapClient.swift index 979d6f8..d590a19 100644 --- a/OpenTDFKit/KASRewrapClient.swift +++ b/OpenTDFKit/KASRewrapClient.swift @@ -761,8 +761,8 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { /// one split ID (`sid`, absent counts as one ID), so any of them yields the /// whole DEK and the first returned is used. A split-key manifest throws /// `KASRewrapError.invalidTDFRequest` before any request is sent — call - /// `rewrapAndUnwrapTDFShares` at each KAS and combine with - /// `TDFDecryptor.combineKeyShares`. With no key access object for this KAS, + /// `rewrapAndUnwrapTDFShares` at each KAS and pass the shares to + /// `TDFDecryptor.decrypt(container:keyShares:)`. With no key access object for this KAS, /// `rewrapTDF` throws `KASRewrapError.invalidTDFRequest`. A permit without a /// session public key throws `KASRewrapError.missingSessionKey`; a wrapped /// key that fails to open (wrong salt, wrong client key, corrupt bytes) @@ -773,7 +773,7 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { let splitIDs = Set(manifest.encryptionInformation.keyAccess.map { $0.sid ?? "" }) guard splitIDs.count <= 1 else { throw KASRewrapError.invalidTDFRequest( - "Split-key manifest (\(splitIDs.count) splits): use rewrapAndUnwrapTDFShares at each KAS and TDFDecryptor.combineKeyShares", + "Split-key manifest (\(splitIDs.count) splits): use rewrapAndUnwrapTDFShares at each KAS and TDFDecryptor.decrypt(container:keyShares:)", ) } let shares = try await rewrapAndUnwrapTDFShares(manifest: manifest) @@ -796,7 +796,7 @@ public final class KASRewrapClient: KASRewrapClientProtocol, Sendable { /// Rewraps every key access object this KAS holds and unwraps each returned /// key with the session key, tagged with its object's split ID. For a /// split-key manifest, collect shares from every KAS and pass them to - /// `TDFDecryptor.combineKeyShares`. + /// `TDFDecryptor.decrypt(container:keyShares:)`. /// - Parameter manifest: The parsed TDF manifest containing key access entries. /// - Returns: One share per permitted key access object at this KAS. public func rewrapAndUnwrapTDFShares(manifest: TDFManifest) async throws -> [TDFKeyShare] { diff --git a/OpenTDFKit/KASService.swift b/OpenTDFKit/KASService.swift index 72ad581..4cac556 100644 --- a/OpenTDFKit/KASService.swift +++ b/OpenTDFKit/KASService.swift @@ -494,28 +494,29 @@ public actor KASService { policyBody: Data?, policyBinding: Data?, ) async throws -> (rewrappedKey: Data, keyID: UUID) { - // Atomically pop the one-time key so concurrent valid callers cannot reuse it. - guard var privateKeyData = await keyStore.popPrivateKey(forPublicKey: kasPublicKey) else { + // Peek first so malformed/unauthorized requests neither consume the one-time key + // nor open a transient `keyNotFound` window for concurrent legitimate callers. + guard var privateKeyData = await keyStore.getPrivateKey(forPublicKey: kasPublicKey) else { throw KASServiceError.keyNotFound } defer { privateKeyData.secureZero() } - let keyID = Self.deterministicUUID(for: kasPublicKey) + let (rewrappedKey, _) = try await rewrapKeyInternal( + ephemeralPublicKey: ephemeralPublicKey, + encryptedKey: encryptedKey, + privateKeyData: privateKeyData, + policyBody: policyBody, + policyBinding: policyBinding, + ) - do { - let (rewrappedKey, _) = try await rewrapKeyInternal( - ephemeralPublicKey: ephemeralPublicKey, - encryptedKey: encryptedKey, - privateKeyData: privateKeyData, - policyBody: policyBody, - policyBinding: policyBinding, - ) - return (rewrappedKey: rewrappedKey, keyID: keyID) - } catch { - // Restore the key so a malformed or unauthorized request cannot burn a one-time key. - await keyStore.store(keyPair: StoredKeyPair(publicKey: kasPublicKey, privateKey: privateKeyData)) - throw error + // Atomically commit one-time consumption; if another valid caller won the race, fail. + guard var consumedKey = await keyStore.popPrivateKey(forPublicKey: kasPublicKey) else { + throw KASServiceError.keyNotFound } + consumedKey.secureZero() + + let keyID = Self.deterministicUUID(for: kasPublicKey) + return (rewrappedKey: rewrappedKey, keyID: keyID) } /// Derives a deterministic RFC 9562 version 8 (custom SHA-256) UUID from the KAS public key bytes. diff --git a/OpenTDFKit/NanoTDF.swift b/OpenTDFKit/NanoTDF.swift index 5bd0623..68de4b9 100644 --- a/OpenTDFKit/NanoTDF.swift +++ b/OpenTDFKit/NanoTDF.swift @@ -99,6 +99,7 @@ public struct NanoTDF: Sendable { public enum NanoTDFError: Error, CustomStringConvertible, Equatable { case payloadTooLarge(Int) + case payloadLengthMismatch(declared: Int, actual: Int) case policyTooLarge(Int) case invalidPolicyBinding @@ -106,6 +107,8 @@ public enum NanoTDFError: Error, CustomStringConvertible, Equatable { switch self { case let .payloadTooLarge(length): "NanoTDF payload length \(length) exceeds the 24-bit limit of 16,777,215 bytes" + case let .payloadLengthMismatch(declared, actual): + "NanoTDF payload declared length \(declared) does not match actual byte count \(actual)" case let .policyTooLarge(length): "NanoTDF embedded policy length \(length) exceeds the 16-bit limit of 65,535 bytes" case .invalidPolicyBinding: @@ -568,7 +571,7 @@ public struct Payload: Sendable { try NanoTDF.validatePayloadLength(Int(length)) try NanoTDF.validatePayloadLength(actualLength) guard Int(length) == actualLength else { - throw NanoTDFError.payloadTooLarge(actualLength) + throw NanoTDFError.payloadLengthMismatch(declared: Int(length), actual: actualLength) } return toData() } diff --git a/OpenTDFKit/TDF/StreamingTDFCrypto.swift b/OpenTDFKit/TDF/StreamingTDFCrypto.swift index cb3e711..cb7e203 100644 --- a/OpenTDFKit/TDF/StreamingTDFCrypto.swift +++ b/OpenTDFKit/TDF/StreamingTDFCrypto.swift @@ -472,8 +472,9 @@ public enum StreamingTDFCrypto { ) throws { guard chunkSize > 0 else { throw StreamingCryptoError.invalidChunkSize } guard !segments.isEmpty else { throw StreamingCryptoError.malformedSegment(0) } - // Multi-segment payloads require a rootSignature to prevent segment reordering/dropping. - if segments.count > 1, rootSignature == nil { + // Require a rootSignature for every payload (including 1-segment) so an attacker + // cannot truncate an N-segment payload down to 1 segment and strip the root. + guard let rootSignature else { throw StreamingCryptoError.integrityCheckFailed } let startOffset = try inputHandle.offset() @@ -549,26 +550,28 @@ public enum StreamingTDFCrypto { throw StreamingCryptoError.malformedSegment(segments.last?.segmentIndex ?? 0) } - if let rootSignature { - 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 - } + 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 } - // Pass 2: every segment and the root signature passed; stream verified plaintext directly to outputHandle. + // Pass 2: stream verified plaintext directly to outputHandle, re-verifying every + // reread segment against its Pass-1 root-authenticated signature before emitting bytes. currentOffset = startOffset - for segment in segments { + for (index, segment) in segments.enumerated() { let segmentSizeInt = Int(segment.encryptedSize) let segmentSize = UInt64(segment.encryptedSize) try inputHandle.seek(toOffset: currentOffset) 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) @@ -583,6 +586,20 @@ public enum StreamingTDFCrypto { totalRead += chunk.count } let tagData = try inputHandle.read(upToCount: 16) ?? Data() + guard tagData.count == 16 else { + throw StreamingCryptoError.malformedSegment(segment.segmentIndex) + } + + let rereadSig = try computeSegmentSignature( + ivData: ivData, + ciphertext: ciphertextAccumulator, + tagData: tagData, + algorithm: segmentHashAlg, + symmetricKey: symmetricKey, + ) + guard CryptoHelper.constantTimeEquals(rereadSig, segmentSignatures[index]) else { + throw StreamingCryptoError.integrityCheckFailed + } let nonce = try AES.GCM.Nonce(data: ivData) let sealed = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertextAccumulator, tag: tagData) @@ -604,11 +621,17 @@ public enum StreamingTDFCrypto { guard !segments.isEmpty else { throw StreamingCryptoError.malformedSegment(0) } - if segments.count > 1, rootSignature == nil { + guard let rootSignature else { throw StreamingCryptoError.integrityCheckFailed } var plaintext = Data() plaintext.reserveCapacity(encryptedPayload.count) + var succeeded = false + defer { + if !succeeded { + plaintext.secureZero() + } + } var segmentSignatures: [Data] = [] segmentSignatures.reserveCapacity(segments.count) var offset = 0 @@ -618,7 +641,6 @@ public enum StreamingTDFCrypto { let segmentSize = Int(exactly: segment.encryptedSize), offset <= encryptedPayload.count, segmentSize <= encryptedPayload.count - offset else { - plaintext.secureZero() throw StreamingCryptoError.malformedSegment(segment.segmentIndex) } @@ -638,7 +660,6 @@ public enum StreamingTDFCrypto { guard let expectedHash = Data(base64Encoded: segment.hash), CryptoHelper.constantTimeEquals(expectedHash, computedSig) else { - plaintext.secureZero() throw StreamingCryptoError.integrityCheckFailed } @@ -652,22 +673,19 @@ public enum StreamingTDFCrypto { } guard offset == encryptedPayload.count else { - plaintext.secureZero() throw StreamingCryptoError.malformedSegment(segments.last?.segmentIndex ?? 0) } - if let rootSignature { - let computedRoot = Data(HMAC.authenticationCode( - for: Data(segmentSignatures.joined()), - using: symmetricKey, - )) - guard let expectedRoot = Data(base64Encoded: rootSignature), - CryptoHelper.constantTimeEquals(expectedRoot, computedRoot) - else { - plaintext.secureZero() - throw StreamingCryptoError.integrityCheckFailed - } + 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 } + succeeded = true return plaintext } } diff --git a/OpenTDFKit/TDF/TDFKAS.swift b/OpenTDFKit/TDF/TDFKAS.swift index 65f4917..57cc941 100644 --- a/OpenTDFKit/TDF/TDFKAS.swift +++ b/OpenTDFKit/TDF/TDFKAS.swift @@ -12,8 +12,8 @@ import Foundation /// out as nonce (12) ‖ ciphertext ‖ tag (16). /// /// A key access object wraps its split's **key share**. For a TDF with a single -/// split the share is the DEK; with several splits the shares are XORed -/// (`TDFDecryptor.combineKeyShares`). +/// split the share is the DEK; with several splits the shares are verified and +/// XORed (`TDFDecryptor.decrypt(container:keyShares:)`). public enum TDFKAS { /// Size of every key share this path accepts. static let shareByteCount = 32 diff --git a/OpenTDFKit/TDF/TDFProcessor.swift b/OpenTDFKit/TDF/TDFProcessor.swift index 33d4809..3bc9d03 100644 --- a/OpenTDFKit/TDF/TDFProcessor.swift +++ b/OpenTDFKit/TDF/TDFProcessor.swift @@ -638,8 +638,9 @@ public struct TDFDecryptor { symmetricKey: share.key, ) } + // Skip a bad replica share so another valid replica for the same split can still succeed. guard bindingValid else { - throw TDFDecryptError.policyBindingFailed + continue } verifiedShares[sid] = TDFCrypto.data(from: share.key) } @@ -761,10 +762,12 @@ public struct TDFDecryptor { return SymmetricKey(data: dek) } - /// Decrypt a Standard TDF payload with its DEK. + /// Decrypt a single-split Standard TDF payload with its DEK. /// /// Checks payload algorithm and key size, verifies segment/root integrity and - /// policy binding, and opens every AES-GCM segment. + /// policy binding, and opens every AES-GCM segment. For multi-split manifests, + /// use `decrypt(container:keyShares:)` or `decrypt(container:privateKeyPEM:)` + /// so every split's share binding is verified before XOR combination. public func decrypt(container: TDFContainer, symmetricKey: SymmetricKey) throws -> Data { try decryptEncryptionInfo( container.manifest.encryptionInformation, diff --git a/OpenTDFKitTests/SecurityAuditRegressionTests.swift b/OpenTDFKitTests/SecurityAuditRegressionTests.swift index ce99a38..e0b58a9 100644 --- a/OpenTDFKitTests/SecurityAuditRegressionTests.swift +++ b/OpenTDFKitTests/SecurityAuditRegressionTests.swift @@ -416,6 +416,8 @@ final class SecurityAuditRegressionTests: XCTestCase { "https://[::ffff:8.8.8.8]/kas", "https://[::7f00:1]/kas", "https://[::169.254.169.254]/kas", + "https://[2002:a9fe:a9fe::]/kas", + "https://[2001:0000:4136:e378:8000:63bf:3fff:fdd2]/kas", "https://[64:ff9b::10.0.0.1]/kas", "https://[ff02::1]/kas", // Userinfo @@ -494,25 +496,28 @@ final class SecurityAuditRegressionTests: XCTestCase { XCTFail("Unexpected error: \(error)") } - // Pre-cancelled task must never hang BoundedHTTPClient.send + // Pre-cancelled task must deterministically throw CancellationError without hanging MockURLProtocol.handler = { req in let resp = HTTPURLResponse(url: req.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! return (resp, Data("ok".utf8)) } let cancelledTask = Task { - try await withTaskCancellationHandler { - try await BoundedHTTPClient.send( - URLRequest(url: URL(string: "https://kas.example.com/cancelled")!), - on: MockURLProtocol.makeSession(), - maxBytes: 1024, - ) - } onCancel: {} + withUnsafeCurrentTask { $0?.cancel() } + return try await BoundedHTTPClient.send( + URLRequest(url: URL(string: "https://kas.example.com/cancelled")!), + on: MockURLProtocol.makeSession(), + maxBytes: 1024, + ) } - cancelledTask.cancel() do { _ = try await cancelledTask.value + XCTFail("Expected cancellation error for pre-cancelled task") + } catch is CancellationError { + // Expected + } catch let urlErr as URLError where urlErr.code == .cancelled { + // Also acceptable if URLSession completed cancellation first } catch { - // Expected cancellation / URLError.cancelled without hanging + XCTFail("Unexpected error for pre-cancelled task: \(error)") } } @@ -696,9 +701,16 @@ final class SecurityAuditRegressionTests: XCTestCase { splitKAO2.policyBinding = TDFCrypto.policyBinding(policy: policy.json, symmetricKey: share2Key) realSplitManifest.encryptionInformation.keyAccess = [splitKAO1, splitKAO2] let realSplitContainer = TDFContainer(manifest: realSplitManifest, payload: result.container.payload) + // Legitimate multi-split decryption via decrypt(container:keyShares:) verifies every share's binding + // and skips a bad replica share ahead of a valid share for the same split. + let badReplicaKey = SymmetricKey(data: Data(repeating: 0x01, count: 32)) let decryptedMulti = try TDFDecryptor().decrypt( container: realSplitContainer, - keyShares: [TDFKeyShare(sid: "s1", key: share1Key), TDFKeyShare(sid: "s2", key: share2Key)], + keyShares: [ + TDFKeyShare(sid: "s1", key: badReplicaKey), + TDFKeyShare(sid: "s1", key: share1Key), + TDFKeyShare(sid: "s2", key: share2Key), + ], ) XCTAssertEqual(decryptedMulti, Data("hello".utf8)) @@ -832,6 +844,24 @@ final class SecurityAuditRegressionTests: XCTestCase { try inHandle.close() try encHandle.close() + // Truncating to 1 segment with nil rootSignature must also be rejected + let seg0OnlyURL = FileManager.default.temporaryDirectory.appendingPathComponent("stream-seg0-\(UUID().uuidString)") + let encBytesAll = try Data(contentsOf: encURL) + let firstSegLen = Int(encResult.segments[0].encryptedSize) + try Data(encBytesAll.prefix(firstSegLen)).write(to: seg0OnlyURL) + defer { try? FileManager.default.removeItem(at: seg0OnlyURL) } + let readSeg0 = try FileHandle(forReadingFrom: seg0OnlyURL) + let outSeg0 = try FileHandle(forWritingTo: outURL) + XCTAssertThrowsError(try StreamingTDFCrypto.decryptPayloadStreamingMultiSegment( + inputHandle: readSeg0, + outputHandle: outSeg0, + segments: [encResult.segments[0]], + symmetricKey: key, + rootSignature: nil, + )) + try readSeg0.close() + try outSeg0.close() + // Missing rootSignature on multi-segment payload must be rejected let readEncMissingRoot = try FileHandle(forReadingFrom: encURL) let outHandleMissingRoot = try FileHandle(forWritingTo: outURL) @@ -1077,6 +1107,15 @@ final class SecurityAuditRegressionTests: XCTestCase { let clamped = hugePolicy.toData() XCTAssertEqual(clamped.count, 2 + Int(UInt16.max)) + let oversizedPayload = Payload(length: 0x0100_0000, iv: Data(count: 3), ciphertext: Data(), mac: Data(count: 16)) + XCTAssertThrowsError(try oversizedPayload.serializedData()) { error in + XCTAssertEqual(error as? NanoTDFError, .payloadTooLarge(0x0100_0000)) + } + let mismatchedPayload = Payload(length: 99, iv: Data(count: 3), ciphertext: Data([1, 2]), mac: Data(count: 16)) + XCTAssertThrowsError(try mismatchedPayload.serializedData()) { error in + XCTAssertEqual(error as? NanoTDFError, .payloadLengthMismatch(declared: 99, actual: 21)) + } + // #22: Unknown identifierType (e.g., 0x40 | 0x01 = 0x41) rejected var badIdData = Data() badIdData.append(Header.magicNumber) diff --git a/OpenTDFKitTests/StreamingTDFCryptoTests.swift b/OpenTDFKitTests/StreamingTDFCryptoTests.swift index 0f1beef..1db2826 100644 --- a/OpenTDFKitTests/StreamingTDFCryptoTests.swift +++ b/OpenTDFKitTests/StreamingTDFCryptoTests.swift @@ -51,6 +51,8 @@ final class StreamingTDFCryptoTests: XCTestCase { hash: tag.base64EncodedString(), ) + let rootSig = Data(HMAC.authenticationCode(for: tag, using: key)).base64EncodedString() + for invalidSize in [-1, 27, Int64(encrypted.count + 1)] { let segment = StreamingTDFCrypto.EncryptedSegment( segmentIndex: 0, @@ -62,6 +64,7 @@ final class StreamingTDFCryptoTests: XCTestCase { encryptedPayload: encrypted, segments: [segment], symmetricKey: key, + rootSignature: rootSig, )) } @@ -69,11 +72,19 @@ final class StreamingTDFCryptoTests: XCTestCase { encryptedPayload: encrypted + Data([0]), segments: [validSegment], symmetricKey: key, + rootSignature: rootSig, + )) + XCTAssertThrowsError(try StreamingTDFCrypto.decryptPayloadMultiSegmentFromMemory( + encryptedPayload: encrypted, + segments: [validSegment], + symmetricKey: key, + rootSignature: nil, )) XCTAssertEqual(try StreamingTDFCrypto.decryptPayloadMultiSegmentFromMemory( encryptedPayload: encrypted, segments: [validSegment], symmetricKey: key, + rootSignature: rootSig, ), Data([1, 2, 3])) }