Files
Si Beaumont 57de8e7cb8 Zero the entire pointee in UnsafeMutablePointer.zeroize (#491)
### Motivation:

We have some helper functions to zero out memory after use. One of these
helper functions provides a `zeroize()` method on
`UnsafeMutablePointer`, which has a subtle bug. It zeros out
`MemoryLayout.size(ofValue: Pointee.self)` instead of
`MemoryLayout<Pointee>.size`, so only the first 8 bytes get zeroed. This
bug is duplicated in CryptoExtras too in a fileprivate helper.

### Modifications:

- Zero the entire pointee in UnsafeMutablePointer.zeroize
- Copy Zeroization helpers from Crypto to CryptoExtras (without the `#if
canImport(CryptoKit)` guard)

### Result:

All the memory that should be zeroed by this helper is actually zeroed.
2026-10-23 11:46:45 +00:00

80 lines
2.1 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(CryptoKit)
@_exported import CryptoKit
#else
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
protocol Zeroization {
mutating func zeroize()
}
extension UnsafeMutablePointer: Zeroization {
/// Zeroizes the pointee
func zeroize() {
let size = MemoryLayout<Pointee>.size
memset_s(self, size, 0, size)
}
}
extension UnsafeMutableRawBufferPointer: Zeroization {
func zeroize() {
memset_s(self.baseAddress!, self.count, 0, self.count)
}
}
extension Array: Zeroization where Element == UInt8 {
/// Zeroizes the array
mutating func zeroize() {
memset_s(&self, self.count, 0, self.count)
}
}
extension Data: Zeroization {
internal mutating func zeroize() {
_ = self.withUnsafeMutableBytes {
memset_s($0.baseAddress!, $0.count, 0, $0.count)
}
}
}
func withUnsafeTemporaryZeroingAllocation<R>(
byteCount: Int,
alignment: Int,
_ body: (UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R {
try withUnsafeTemporaryAllocation(byteCount: byteCount, alignment: alignment) { buffer in
defer { buffer.zeroize() }
return try body(buffer)
}
}
func withTemporaryZeroingAllocation<R>(
byteCount: Int,
alignment: Int,
_ body: (inout OutputRawSpan) throws -> R
) rethrows -> R {
try withUnsafeTemporaryZeroingAllocation(byteCount: byteCount, alignment: alignment) { buffer in
var output = OutputRawSpan(buffer: buffer, initializedCount: 0)
return try body(&output)
}
}
#endif // canImport(CryptoKit)