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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 33 additions & 10 deletions OpenTDFKit/BinaryParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
}

Expand All @@ -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 {
Expand Down Expand Up @@ -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)
}
Expand Down
233 changes: 150 additions & 83 deletions OpenTDFKit/CryptoHelper.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import CommonCrypto
import CryptoKit
import CryptoSwift
import Foundation

/// Enum representing the KAS key curves supported for NanoTDF Payload Key Access.
Expand Down Expand Up @@ -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<SHA256>.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.
Expand Down Expand Up @@ -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
}

Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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
}

Expand All @@ -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
Expand All @@ -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
}
}
4 changes: 3 additions & 1 deletion OpenTDFKit/KASBulkRewrap.swift
Original file line number Diff line number Diff line change
Expand Up @@ -349,9 +349,11 @@ 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)
{
defer { dek.secureZero() }
return .permitted(SymmetricKey(data: dek))
}
unwrapFailed = true
Expand Down
Loading
Loading