From ab0beab369649acbb4fba44064109954028bde19 Mon Sep 17 00:00:00 2001 From: Si Beaumont Date: Mon, 2 Nov 2026 08:31:17 +0000 Subject: [PATCH] Zero temporary buffers that hold key material and reduce more allocations (#493) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Motivation: AES-KeyWrap unwrap, ML-KEM decapsulation, PBKDF2, and scrypt each write the key they return into a temporary buffer, copy it into a `SymmetricKey`, and free the buffer without zeroing it. The `SymmetricKey` stores its copy in `SecureBytes`, which zeroes the copy before freeing it. Nothing zeroes the original. AES-KeyWrap and ML-KEM can write the key directly into the `SymmetricKey`, as X-Wing already does. That removes both the buffer and the copy. PBKDF2 and scrypt can't, because they are in CryptoExtras and `SymmetricKey(unsafeUninitializedCapacity:initializingWith:)` is internal to Crypto. They keep their buffer and zero it after the copy. Moving that buffer onto the stack made them twice as slow. ### Modifications: - Add benchmarks for AES-KeyWrap, ML-KEM, PBKDF2, and scrypt - Unwrap AES-KeyWrap keys straight into the `SymmetricKey` - Decapsulate ML-KEM shared secrets straight into the `SymmetricKey`. Regenerating `MLKEM_boring.swift` from its `.gyb` also drops five `@available` attributes that were only ever in the generated file. - Zero the PBKDF2 and scrypt derived key buffers ### Result: - After the call returns, no temporary buffer still contains the key. - `AES.KeyWrap.unwrap` makes 2 allocations instead of 3 and is about 6% faster. - `MLKEM768.PrivateKey.decapsulate` makes 2 allocations instead of 4. - `KDF.Insecure.PBKDF2.deriveKey` and `KDF.Scrypt.deriveKey` make the same number of allocations and take the same time as before. ### Benchmarks: The tables come from `swift package benchmark --metric mallocCountTotal --metric wallClock`. ``` aes-keywrap-unwrap (before) ╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ Malloc (total) * │ 3 │ 3 │ 3 │ 3 │ 3 │ 3 │ 3 │ 5 │ ├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Time (wall clock) (ns) * │ 597 │ 601 │ 614 │ 621 │ 630 │ 630 │ 630 │ 5 │ ╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ aes-keywrap-unwrap (after) ╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ Malloc (total) * │ 2 │ 2 │ 2 │ 2 │ 2 │ 2 │ 2 │ 5 │ ├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Time (wall clock) (ns) * │ 563 │ 564 │ 578 │ 578 │ 581 │ 581 │ 581 │ 5 │ ╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ mlkem768-decapsulate (before) ╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ Malloc (total) * │ 4 │ 4 │ 4 │ 4 │ 4 │ 4 │ 4 │ 10 │ ├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Time (wall clock) (μs) * │ 48 │ 49 │ 50 │ 51 │ 51 │ 51 │ 51 │ 10 │ ╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ mlkem768-decapsulate (after) ╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕ │ Metric │ p0 │ p25 │ p50 │ p75 │ p90 │ p99 │ p100 │ Samples │ ╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ Malloc (total) * │ 2 │ 2 │ 2 │ 2 │ 2 │ 2 │ 2 │ 10 │ ├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤ │ Time (wall clock) (μs) * │ 46 │ 48 │ 49 │ 51 │ 51 │ 51 │ 51 │ 10 │ ╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛ ``` --- Benchmarks/Benchmarks/Benchmarks.swift | 95 +++++++++++++++++++ .../Crypto/KEM/BoringSSL/MLKEM_boring.swift | 41 ++++---- .../KEM/BoringSSL/MLKEM_boring.swift.gyb | 18 ++-- .../BoringSSL/AESWrap_boring.swift | 6 +- .../PBKDF2/BoringSSL/PBKDF2_boring.swift | 3 +- .../BoringSSL/PBKDF2_commoncrypto.swift | 3 +- .../Scrypt/BoringSSL/Scrypt_boring.swift | 3 +- 7 files changed, 130 insertions(+), 39 deletions(-) diff --git a/Benchmarks/Benchmarks/Benchmarks.swift b/Benchmarks/Benchmarks/Benchmarks.swift index 84cbe8fe..39943294 100644 --- a/Benchmarks/Benchmarks/Benchmarks.swift +++ b/Benchmarks/Benchmarks/Benchmarks.swift @@ -254,4 +254,99 @@ let benchmarks: @Sendable () -> Void = { ) } } + + Benchmark( + "aes-keywrap-unwrap", + configuration: Benchmark.Configuration( + metrics: defaultMetrics, + scalingFactor: .mega, + maxDuration: .seconds(10_000_000), + maxIterations: 5 + ) + ) { benchmark in + let kek = SymmetricKey(size: .bits256) + let wrapped = try AES.KeyWrap.wrap(SymmetricKey(size: .bits256), using: kek) + + benchmark.startMeasurement() + + for _ in benchmark.scaledIterations { + blackHole(try AES.KeyWrap.unwrap(wrapped, using: kek)) + } + } + + if #available(macOS 26.0, *) { + Benchmark( + "mlkem768-decapsulate", + configuration: Benchmark.Configuration( + metrics: defaultMetrics, + scalingFactor: .kilo, + maxDuration: .seconds(10_000_000), + maxIterations: 10 + ) + ) { benchmark in + let privateKey = try MLKEM768.PrivateKey() + let encapsulated = try privateKey.publicKey.encapsulate().encapsulated + + benchmark.startMeasurement() + + for _ in benchmark.scaledIterations { + blackHole(try privateKey.decapsulate(encapsulated)) + } + } + } + + Benchmark( + "pbkdf2-sha256-derive", + configuration: Benchmark.Configuration( + metrics: defaultMetrics, + scalingFactor: .kilo, + maxDuration: .seconds(10_000_000), + maxIterations: 10 + ) + ) { benchmark in + let password = Data("benchmark password".utf8) + let salt = Data("benchmark salt".utf8) + + benchmark.startMeasurement() + + for _ in benchmark.scaledIterations { + blackHole( + try KDF.Insecure.PBKDF2.deriveKey( + from: password, + salt: salt, + using: .sha256, + outputByteCount: 32, + unsafeUncheckedRounds: 1_000 + ) + ) + } + } + + Benchmark( + "scrypt-derive", + configuration: Benchmark.Configuration( + metrics: defaultMetrics, + scalingFactor: .kilo, + maxDuration: .seconds(10_000_000), + maxIterations: 3 + ) + ) { benchmark in + let password = Data("benchmark password".utf8) + let salt = Data("benchmark salt".utf8) + + benchmark.startMeasurement() + + for _ in benchmark.scaledIterations { + blackHole( + try KDF.Scrypt.deriveKey( + from: password, + salt: salt, + outputByteCount: 32, + rounds: 1 << 10, + blockSize: 8, + parallelism: 1 + ) + ) + } + } } diff --git a/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift b/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift index c51c616c..11e4c7ea 100644 --- a/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift +++ b/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift @@ -33,7 +33,6 @@ import Foundation @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MLKEM768 { /// A ML-KEM-768 private key. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey { private var backing: Backing @@ -150,14 +149,14 @@ extension MLKEM768 { throw CryptoKitError.incorrectParameterSize } - var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount) - - let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in + return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) { + symmetricKeyDataPtr, + count in let bytes: ContiguousBytes = encapsulated.regions.count == 1 ? encapsulated.regions.first! : Array(encapsulated) - return bytes.withUnsafeBytes { encapsulatedPtr in + let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in CCryptoBoringSSL_MLKEM768_decap( symmetricKeyDataPtr.baseAddress, encapsulatedPtr.baseAddress, @@ -165,13 +164,13 @@ extension MLKEM768 { &self.key ) } - } - guard rc == 1 else { - throw CryptoKitError.internalBoringSSLError() - } + guard rc == 1 else { + throw CryptoKitError.internalBoringSSLError() + } - return SymmetricKey(data: symmetricKeyData) + count = MLKEM.sharedSecretByteCount + } } } } @@ -180,7 +179,6 @@ extension MLKEM768 { @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MLKEM768 { /// A ML-KEM-768 public key. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct InternalPublicKey: @unchecked Sendable, KEMPublicKey { private var backing: Backing @@ -302,7 +300,6 @@ extension MLKEM768 { @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MLKEM1024 { /// A ML-KEM-1024 private key. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey { private var backing: Backing @@ -419,14 +416,14 @@ extension MLKEM1024 { throw CryptoKitError.incorrectParameterSize } - var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount) - - let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in + return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) { + symmetricKeyDataPtr, + count in let bytes: ContiguousBytes = encapsulated.regions.count == 1 ? encapsulated.regions.first! : Array(encapsulated) - return bytes.withUnsafeBytes { encapsulatedPtr in + let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in CCryptoBoringSSL_MLKEM1024_decap( symmetricKeyDataPtr.baseAddress, encapsulatedPtr.baseAddress, @@ -434,13 +431,13 @@ extension MLKEM1024 { &self.key ) } - } - guard rc == 1 else { - throw CryptoKitError.internalBoringSSLError() - } + guard rc == 1 else { + throw CryptoKitError.internalBoringSSLError() + } - return SymmetricKey(data: symmetricKeyData) + count = MLKEM.sharedSecretByteCount + } } } } @@ -449,7 +446,6 @@ extension MLKEM1024 { @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MLKEM1024 { /// A ML-KEM-1024 public key. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) struct InternalPublicKey: @unchecked Sendable, KEMPublicKey { private var backing: Backing @@ -568,7 +564,6 @@ extension MLKEM1024 { private static let ciphertextByteCount = Int(MLKEM1024_CIPHERTEXT_BYTES) } -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) enum MLKEM { /// The size of the seed in bytes. static let seedByteCount = 64 diff --git a/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift.gyb b/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift.gyb index 825fe21b..77c0ccb3 100644 --- a/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift.gyb +++ b/Sources/Crypto/KEM/BoringSSL/MLKEM_boring.swift.gyb @@ -153,14 +153,14 @@ extension MLKEM${parameter_set} { throw CryptoKitError.incorrectParameterSize } - var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount) - - let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in + return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) { + symmetricKeyDataPtr, + count in let bytes: ContiguousBytes = encapsulated.regions.count == 1 ? encapsulated.regions.first! : Array(encapsulated) - return bytes.withUnsafeBytes { encapsulatedPtr in + let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in CCryptoBoringSSL_MLKEM${parameter_set}_decap( symmetricKeyDataPtr.baseAddress, encapsulatedPtr.baseAddress, @@ -168,13 +168,13 @@ extension MLKEM${parameter_set} { &self.key ) } - } - guard rc == 1 else { - throw CryptoKitError.internalBoringSSLError() - } + guard rc == 1 else { + throw CryptoKitError.internalBoringSSLError() + } - return SymmetricKey(data: symmetricKeyData) + count = MLKEM.sharedSecretByteCount + } } } } diff --git a/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift b/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift index 29b74c42..5f38397b 100644 --- a/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift +++ b/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift @@ -72,8 +72,8 @@ enum BoringSSLAESWRAPImpl { key: SymmetricKey, contiguousWrappedKey: WrappedKey ) throws -> SymmetricKey { - let unwrapped = try contiguousWrappedKey.withUnsafeBytes { inPtr in - try [UInt8](unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in + try contiguousWrappedKey.withUnsafeBytes { inPtr in + try SymmetricKey(unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in let rc = try key.withUnsafeAESKEY(mode: .decrypting) { aesKey in CCryptoBoringSSL_AES_unwrap_key( aesKey, @@ -93,8 +93,6 @@ enum BoringSSLAESWRAPImpl { count = Int(rc) } } - - return SymmetricKey(data: unwrapped) } } diff --git a/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_boring.swift b/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_boring.swift index 2fce41a0..f93fdf6e 100644 --- a/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_boring.swift +++ b/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_boring.swift @@ -43,8 +43,9 @@ internal struct BoringSSLPBKDF2 { outputByteCount: Int, rounds: Int ) throws -> SymmetricKey { - // This should be SecureBytes, but we can't use that here. + // SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out. var derivedKeyData = Data(count: outputByteCount) + defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } } let rc = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt) diff --git a/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_commoncrypto.swift b/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_commoncrypto.swift index 5926bbc4..2ed98d31 100644 --- a/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_commoncrypto.swift +++ b/Sources/CryptoExtras/Key Derivation/PBKDF2/BoringSSL/PBKDF2_commoncrypto.swift @@ -39,8 +39,9 @@ internal struct CommonCryptoPBKDF2 { outputByteCount: Int, rounds: Int ) throws -> SymmetricKey { - // This should be SecureBytes, but we can't use that here. + // SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out. var derivedKeyData = Data(count: outputByteCount) + defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } } let derivationStatus = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt) diff --git a/Sources/CryptoExtras/Key Derivation/Scrypt/BoringSSL/Scrypt_boring.swift b/Sources/CryptoExtras/Key Derivation/Scrypt/BoringSSL/Scrypt_boring.swift index ce7cbca0..c6e2972a 100644 --- a/Sources/CryptoExtras/Key Derivation/Scrypt/BoringSSL/Scrypt_boring.swift +++ b/Sources/CryptoExtras/Key Derivation/Scrypt/BoringSSL/Scrypt_boring.swift @@ -81,8 +81,9 @@ internal struct BoringSSLScrypt { parallelism: Int, maxMemory: Int? = nil ) throws -> SymmetricKey { - // This should be SecureBytes, but we can't use that here. + // SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out. var derivedKeyData = Data(count: outputByteCount) + defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } } // This computes the maximum amount of memory that will be used by the scrypt algorithm with an additional memory page to spare. This value will be used by the BoringSSL as the memory limit for the algorithm. // An additional memory page is added to the computed value (using POSIX specification) to ensure that the memory limit is not too tight.