Compare commits

...
3 Commits
Author SHA1 Message Date
Si Beaumont 47d3869a72 Merge commit from fork
* Fix double-free when RSA key init from bytes fails

Motivation:

When initializing an RSA public key from DER or PEM bytes throws an error,
we double-free of the `EVP_PKEY*`: first in the catch block, then in the
backing `deinit`. The first of these should be removed.

Modifications:

Remove the duplicative call to `EVP_PKEY_free`.

Result:

Fixed double-free of `EVP_PKEY*` when failing to initialize RSA public
key from bytes.

Testing:

Tests have been added that reliably fail under ASan:

```console
% swift --version
Swift version 6.3.2 (swift-6.3.2-RELEASE)
Target: aarch64-unknown-linux-gnu

% env ASAN_OPTIONS=detect_leaks=0 swift test -c release --sanitize=address \
  --filter test_invalidPEMPublicKeyThrowsWithoutDoubleFree \
  --filter test_invalidDERPublicKeyThrowsWithoutDoubleFree

Test Suite 'Selected tests' started at 2026-07-06 09:36:58.468
Test Suite 'TestRSASigning' started at 2026-07-06 09:36:58.469
Test Case 'TestRSASigning.test_invalidDERPublicKeyThrowsWithoutDoubleFree' started at 2026-07-06 09:36:58.469
Test Case 'TestRSASigning.test_invalidDERPublicKeyThrowsWithoutDoubleFree' passed (0.001 seconds)
Test Case 'TestRSASigning.test_invalidPEMPublicKeyThrowsWithoutDoubleFree' started at 2026-07-06 09:36:58.470
Test Case 'TestRSASigning.test_invalidPEMPublicKeyThrowsWithoutDoubleFree' passed (0.001 seconds)
Test Suite 'TestRSASigning' passed at 2026-07-06 09:36:58.471
         Executed 2 tests, with 0 failures (0 unexpected) in 0.002 (0.002) seconds
Test Suite 'Selected tests' passed at 2026-07-06 09:36:58.471
         Executed 2 tests, with 0 failures (0 unexpected) in 0.002 (0.002) seconds
◇ Test run started.
↳ Testing Library Version: 6.3.2 (70eff261d7f462c)
↳ Target Platform: aarch64-unknown-linux-gnu
✔ Test run with 0 tests in 0 suites passed after 0.001 seconds.
```

* Have only one designated init for BoringSSLRSAPublicKey.Backing
2026-07-16 13:29:36 +01:00
Si Beaumont c3d9fc8938 Back AES-CBC with BoringSSL and constant-time PKCS#7 unpadding (#448)
### Motivation:

Our AES-CBC padding check is a padding-oracle timing side channel.
Validation short-circuits on the first mismatching byte, so the time
taken leaks padding validity; an attacker with a decryption oracle could
recover plaintext without the key. The AES core is already
BoringSSL-backed, so the remaining fix is to move the CBC mode onto
BoringSSL and update padding removal to be constant-time.

Aside: padding removal cannot be delegated to BoringSSL, whose generic
unpad is itself a documented padding oracle absent authentication.

### Modifications:

- Replace the Swift CBC block loop in `AES._CBC` with BoringSSL's
`AES_cbc_encrypt`.
- Add padding on encrypt in Swift, since `AES_cbc_encrypt` does not pad.
- Replace `trimPadding` with `removingPKCS7PaddingConstantTime`
- Add regression tests rejecting over-long pad lengths.
- Add unpad tests for every valid length.
- Add unpad tests for every corruption position.

### Result:

AES-CBC is BoringSSL-backed and padding validation runs in constant
time, removing a timing side channel.
2026-07-16 12:28:36 +00:00
Si Beaumont 1ca42a1885 Update cross-platform dependencies in README (#446)
### Motivation:

Swift Crypto 4.0 included SHA3 APIs, which required a backing
implementation on non-Apple platforms. We brought in libXCKP for this
purpose, similar to how we use BoringSSL for the implementation of the
rest of CryptoKit API on non-Apple platforms. The README includes
details of how the code is organised but was not updated to reflect this
change.

### Modifications:

- Update the backend implementation section to include XCKP alongside
BoringSSL
- Add an acknowledgments section to the README

### Result:

The README now includes details of both our backing dependencies, not
just BoringSSL.

Fixes #439.
2026-07-01 10:08:47 +00:00
8 changed files with 323 additions and 239 deletions

No files matched your search

+11 -6
View File
@@ -31,10 +31,11 @@ When building Swift Crypto for use on an Apple platform where CryptoKit is alrea
When building Swift Crypto for use on Linux or Windows, Swift Crypto builds substantially more code. In particular, we build:
1. A vendored copy of BoringSSL's libcrypto.
2. The common API of Swift Crypto and CryptoKit.
3. The backing implementation of this common API, which calls into BoringSSL.
2. A vendored copy of XKCP's libXKCP.
3. The common API of Swift Crypto and CryptoKit.
4. The backing implementation of this common API, which calls into BoringSSL or XKCP.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The backing BoringSSL-based implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIS predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL implementation of the library in your application, no matter the platform.
The API code, and some cryptographic primitives which are directly implemented in Swift, are exactly the same for both Apple CryptoKit and Swift Crypto. The BoringSSL/XKCP backing implementation is unique to Swift Crypto. In addition, there is another product, `CryptoExtras`, which provides additional functionality that is not offered in CryptoKit, which contains cryptographic APIs predominantly useful in the server ecosystem. **Note**: if you depend on CryptoExtras you'll bundle the BoringSSL/XKCP implementation of the library in your application, no matter the platform.
## Evolution
@@ -48,11 +49,11 @@ Note that Swift Crypto does not intend to support all possible cryptographic pri
### Code Organisation
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring` or are in a `BoringSSL` directory, or if they are not.
Files in this repository are divided into two groups, based on whether they have a name that ends in `_boring`/`_xkcp` or are in a `BoringSSL`/`XKCP` directory, or if they are not.
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or access a BoringSSL API, it needs to be marked this way.
Files that meet the above criteria are specific to the Swift Crypto implementation. Changes to these files can be made fairly easily, so long as they meet the criteria below. If your file needs to `import CCryptoBoringSSL` or `import CXKCP` or access a BoringSSL or XKCP API, it needs to be marked this way.
Files that do not have the `_boring` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
Files that do not have the `_boring` or `_xkcp` suffix are part of the public API of CryptoKit. Changing these requires passing a higher bar, as any change in these files must be accompanied by a change in CryptoKit itself.
## Contributing
@@ -146,3 +147,7 @@ To do so, please use the following dependency in your `Package.swift`:
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, change `let development = false` to `let development = true`, as this will force Swift Crypto to build its public API.
## Acknowledgements
This project contains source code from the BoringSSL and XKCP projects.
+5 -91
View File
@@ -25,19 +25,6 @@ extension AES {
/// suite.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
public enum _CBC {
private static var blockSize: Int { 16 }
private static func encryptBlockInPlace(
_ plaintext: inout Block,
priorCiphertextBlock: Block,
using key: SymmetricKey
) throws {
assert([128, 192, 256].contains(key.bitCount))
plaintext ^= priorCiphertextBlock
try AES.permute(&plaintext, key: key)
}
/// Encrypts data using AES-CBC.
///
/// - Parameters:
@@ -60,44 +47,7 @@ extension AES {
///
/// - Note: If `noPadding` is set to `true`, `plainText` has to be a multiple of the blockSize (16 bytes). Otherwise an error will be thrown.
public static func encrypt<Plaintext: DataProtocol>(_ plaintext: Plaintext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
let requiresFullPaddingBlock = (plaintext.count % AES._CBC.blockSize) == 0
if noPadding && !requiresFullPaddingBlock {
throw CryptoKitError.incorrectParameterSize
}
var ciphertext = Data()
ciphertext.reserveCapacity(plaintext.count + Self.blockSize) // Room for padding.
var previousBlock = Block(iv)
var plaintext = plaintext[...]
while plaintext.count > 0 {
var block = Block(blockBytes: plaintext.prefix(Self.blockSize))
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
ciphertext.append(contentsOf: block)
previousBlock = block
plaintext = plaintext.dropFirst(Self.blockSize)
}
if requiresFullPaddingBlock && !noPadding {
var block = Block.paddingBlock
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
ciphertext.append(contentsOf: block)
}
return ciphertext
}
private static func decryptBlockInPlace(_ ciphertext: inout Block, priorCiphertextBlock: Block, using key: SymmetricKey) throws {
assert([128, 192, 256].contains(key.bitCount))
try AES.inversePermute(&ciphertext, key: key)
ciphertext ^= priorCiphertextBlock
try OpenSSLAESCBCImpl.encrypt(plaintext, using: key, iv: iv, noPadding: noPadding)
}
/// Decrypts data using AES-CBC.
@@ -120,29 +70,7 @@ extension AES {
/// - noPadding: If this is set to `true`, padding won't be removed.
/// - Returns: The decrypted message.
public static func decrypt<Ciphertext: DataProtocol>(_ ciphertext: Ciphertext, using key: SymmetricKey, iv: AES._CBC.IV, noPadding: Bool) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
var plaintext = Data()
plaintext.reserveCapacity(ciphertext.count)
var previousBlock = Block(iv)
var ciphertext = ciphertext[...]
while ciphertext.count > 0 {
let ctBlock = Block(blockBytes: ciphertext.prefix(Self.blockSize))
var block = ctBlock
try Self.decryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
plaintext.append(contentsOf: block)
previousBlock = ctBlock
ciphertext = ciphertext.dropFirst(Self.blockSize)
}
if !noPadding {
try plaintext.trimPadding()
}
return plaintext
try OpenSSLAESCBCImpl.decrypt(ciphertext, using: key, iv: iv, noPadding: noPadding)
}
}
}
@@ -194,7 +122,7 @@ extension AES._CBC {
0, 0, 0, 0, 0, 0, 0, 0
)
withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
Swift.withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
bytesPtr.copyBytes(from: ivBytes)
}
}
@@ -205,24 +133,10 @@ extension AES._CBC {
Array(unsafeRawBufferPointer).makeIterator()
}
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
fileprivate mutating func trimPadding() throws {
guard let paddingBytes = self.last else {
// Degenerate case, empty string. This is forbidden:
// we must always pad.
throw CryptoKitError.incorrectParameterSize
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeMutableBytes(of: &self.ivBytes, body)
}
guard paddingBytes > 0 &&
self.count >= paddingBytes &&
self.suffix(Int(paddingBytes)).allSatisfy({ $0 == paddingBytes }) else {
throw CryptoKitError.incorrectParameterSize
}
self = self.dropLast(Int(paddingBytes))
}
}
@@ -118,8 +118,6 @@ extension AES {
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
struct Block {
private static var blockSize: Int { 16 }
typealias BlockBytes = (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
@@ -135,70 +133,9 @@ extension AES {
)
}
init(_ blockBytes: BlockBytes) {
self.blockBytes = blockBytes
}
init(_ iv: AES._CBC.IV) {
self.blockBytes = iv.ivBytes
}
init<BlockBytes: Collection>(blockBytes: BlockBytes) where BlockBytes.Element == UInt8 {
// The block size is always 16. Pad out past there.
precondition(blockBytes.count <= Self.blockSize)
self.blockBytes = (
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
)
Swift.withUnsafeMutableBytes(of: &self.blockBytes) { bytesPtr in
bytesPtr.copyBytes(from: blockBytes)
// Early exit here.
if blockBytes.count == Self.blockSize {
return
}
var remainingBytes = bytesPtr.dropFirst(blockBytes.count)
let padByte = UInt8(remainingBytes.count)
for index in remainingBytes.indices {
remainingBytes[index] = padByte
}
}
}
static var paddingBlock: Block {
// The padding block is a full block of value blocksize.
let value = UInt8(truncatingIfNeeded: Self.blockSize)
return Block((
value, value, value, value, value, value, value, value,
value, value, value, value, value, value, value, value
))
}
func withUnsafeBytes<ReturnType>(_ body: (UnsafeRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeBytes(of: self.blockBytes, body)
}
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
return try Swift.withUnsafeMutableBytes(of: &self.blockBytes, body)
}
static func ^= (lhs: inout Block, rhs: Block) {
// Ideally we'd not use raw pointers for this.
lhs.withUnsafeMutableBytes { lhsPtr in
rhs.withUnsafeBytes { rhsPtr in
assert(lhsPtr.count == Self.blockSize)
assert(rhsPtr.count == Self.blockSize)
for index in 0..<Self.blockSize {
lhsPtr[index] ^= rhsPtr[index]
}
}
}
}
}
private static func isValidKey(_ key: SymmetricKey) -> Bool {
@@ -210,52 +147,3 @@ extension AES {
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension AES.Block: RandomAccessCollection, MutableCollection {
var startIndex: Int {
0
}
var endIndex: Int {
Self.blockSize
}
subscript(position: Int) -> UInt8 {
get {
precondition(position >= 0)
precondition(position < Self.blockSize)
return self.withUnsafeBytes { $0[position] }
}
set {
precondition(position >= 0)
precondition(position < Self.blockSize)
self.withUnsafeMutableBytes { $0[position] = newValue }
}
}
func withContiguousStorageIfAvailable<ReturnValue>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> ReturnValue)
rethrows -> ReturnValue? {
return try withUnsafePointer(to: self.blockBytes) { tuplePtr in
// Homogeneous tuples are always bound to the element type as well as to their own type.
let retyped = UnsafeRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
let bufferised = UnsafeBufferPointer(start: retyped, count: Self.blockSize)
return try body(bufferised)
}
}
mutating func withContiguousMutableStorageIfAvailable<ReturnValue>(
_ body: (inout UnsafeMutableBufferPointer<UInt8>) throws -> ReturnValue)
rethrows -> ReturnValue? {
return try withUnsafeMutablePointer(to: &self.blockBytes) { tuplePtr in
// Homogeneous tuples are always bound to the element type as well as to their own type.
let retyped = UnsafeMutableRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
var bufferised = UnsafeMutableBufferPointer(start: retyped, count: Self.blockSize)
return try body(&bufferised)
}
}
}
@@ -0,0 +1,189 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2026 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
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CCryptoBoringSSL
import Crypto
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
@usableFromInline
enum OpenSSLAESCBCImpl {
private static let blockSize = 16
@usableFromInline
enum Direction {
case encrypt
case decrypt
@usableFromInline
var _boringSSLParameter: Int32 {
switch self {
case .encrypt: AES_ENCRYPT
case .decrypt: AES_DECRYPT
}
}
}
/// Encrypts plaintext using AES-CBC.
///
/// PKCS#7 padding is added unless `noPadding` is set, in which case the plaintext must
/// already be a whole number of blocks.
static func encrypt<Plaintext: DataProtocol>(
_ plaintext: Plaintext,
using key: SymmetricKey,
iv: AES._CBC.IV,
noPadding: Bool
) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
// With padding disabled the input must be a whole number of blocks.
if noPadding && (plaintext.count % Self.blockSize != 0) {
throw CryptoKitError.incorrectParameterSize
}
// AES_cbc_encrypt performs no padding, so PKCS#7 is applied here.
var padded = Data(plaintext)
if !noPadding {
// PKCS#7 always appends 1...blockSize bytes (a full block when already aligned).
let padLength = Self.blockSize - (plaintext.count % Self.blockSize)
let padding = repeatElement(UInt8(padLength), count: padLength)
padded.append(contentsOf: padding)
}
return padded.withUnsafeBytes { plaintextPtr in
Self._cipher(.encrypt, plaintextPtr, using: key, iv: iv)
}
}
/// Decrypts ciphertext using AES-CBC.
///
/// BoringSSL runs with padding disabled and, unless `noPadding` is set, PKCS#7 padding is
/// removed here in constant time. BoringSSL's own PKCS#7 removal is not constant-time (it is a
/// documented padding oracle absent authentication), so it must not be delegated.
static func decrypt<Ciphertext: DataProtocol>(
_ ciphertext: Ciphertext,
using key: SymmetricKey,
iv: AES._CBC.IV,
noPadding: Bool
) throws -> Data {
guard [128, 192, 256].contains(key.bitCount) else {
throw CryptoKitError.incorrectKeySize
}
// CBC ciphertext is always a whole number of non-empty blocks.
guard ciphertext.count > 0, ciphertext.count % Self.blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}
let contiguousCiphertext = Data(ciphertext)
let plaintext = contiguousCiphertext.withUnsafeBytes { ciphertextPtr in
Self._cipher(.decrypt, ciphertextPtr, using: key, iv: iv)
}
return noPadding ? plaintext : try plaintext.removingPKCS7PaddingConstantTime(blockSize: Self.blockSize)
}
/// Runs raw AES-CBC in the given direction over a single contiguous buffer.
///
/// `AES_cbc_encrypt` performs no padding, so `input` must be a whole number of blocks and the
/// output has the same length. PKCS#7 is applied and removed by the callers.
@usableFromInline
static func _cipher(
_ direction: Direction,
_ input: UnsafeRawBufferPointer,
using key: SymmetricKey,
iv: AES._CBC.IV
) -> Data {
precondition(input.count % Self.blockSize == 0)
var output = Data(count: input.count)
var iv = iv
key.withUnsafeBytes { keyPtr in
// AES_cbc_encrypt advances the IV in place, so operate on our own copy.
iv.withUnsafeMutableBytes { ivPtr in
var key = AES_KEY()
switch direction {
case .encrypt:
precondition(
CCryptoBoringSSL_AES_set_encrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
)
case .decrypt:
precondition(
CCryptoBoringSSL_AES_set_decrypt_key(keyPtr.baseAddress, UInt32(keyPtr.count * 8), &key) == 0
)
}
output.withUnsafeMutableBytes { outputPtr in
CCryptoBoringSSL_AES_cbc_encrypt(
input.baseAddress,
outputPtr.baseAddress,
input.count,
&key,
ivPtr.baseAddress,
direction._boringSSLParameter
)
}
}
}
return output
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension Data {
/// Removes PKCS#7 padding in constant time with respect to the padding bytes.
fileprivate func removingPKCS7PaddingConstantTime(blockSize: Int = 16) throws -> Data {
// The total length is not secret, so branching on it is safe.
guard self.count >= blockSize, self.count % blockSize == 0 else {
throw CryptoKitError.incorrectParameterSize
}
let padLength = self.last!
let lastBlock = self.suffix(blockSize)
// Validate padding in constant time.
var bad: UInt32 = 0
// A valid PKCS#7 pad length is 1...blockSize.
bad |= constantTimeLessThanOrEqual(padLength, 0)
bad |= constantTimeLessThanOrEqual(UInt8(blockSize + 1), padLength)
// We MUST operate on every byte in the block, and each byte in the padding region MUST equal `padLength`.
for index in lastBlock.indices {
let byte = UInt32(lastBlock[index])
let distanceFromEnd = self.endIndex - index
let inPadding = constantTimeLessThanOrEqual(UInt8(distanceFromEnd), padLength)
bad |= inPadding & (byte ^ UInt32(padLength))
}
// Throw if padding was invalid.
guard bad == 0 else {
throw CryptoKitError.incorrectParameterSize
}
// Drop the padding.
return self.dropLast(Int(padLength))
}
}
/// Returns `0xFFFFFFFF` if `lhs <= rhs`, otherwise `0`, without a data-dependent branch.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
private func constantTimeLessThanOrEqual(_ lhs: UInt8, _ rhs: UInt8) -> UInt32 {
// `lhs - rhs - 1` is negative iff `lhs <= rhs`; propagate its sign bit across the word.
let difference = Int32(lhs) - Int32(rhs) - 1
return UInt32(bitPattern: difference >> 31)
}
+1
View File
@@ -18,6 +18,7 @@ add_library(CryptoExtras
"AES/AES_CTR.swift"
"AES/AES_GCM_SIV.swift"
"AES/Block Function.swift"
"AES/BoringSSL/AES_CBC_boring.swift"
"AES/BoringSSL/AES_CFB_boring.swift"
"AES/BoringSSL/AES_CTR_boring.swift"
"AES/BoringSSL/AES_GCM_SIV_boring.swift"
+21 -30
View File
@@ -222,17 +222,17 @@ extension BoringSSLRSAPublicKey {
self.pointer = pointer
}
fileprivate init(copying other: Backing) {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
fileprivate convenience init(copying other: Backing) {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(
CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer)
)
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
fileprivate init(pemRepresentation: String) throws {
fileprivate convenience init(pemRepresentation: String) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
var pemRepresentation = pemRepresentation
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
@@ -248,23 +248,19 @@ extension BoringSSLRSAPublicKey {
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
do {
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
throw error
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
}
fileprivate convenience init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
if derRepresentation.regions.count == 1 {
try self.init(contiguousDerRepresentation: derRepresentation.regions.first!)
@@ -274,8 +270,8 @@ extension BoringSSLRSAPublicKey {
}
}
private init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
private convenience init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
// fall back to the PKCS#1 form if that parse fails.
@@ -290,25 +286,20 @@ extension BoringSSLRSAPublicKey {
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
do {
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
} catch {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
throw error
}
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
}
}
fileprivate init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
fileprivate convenience init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.init(takingOwnershipOf: CCryptoBoringSSL_EVP_PKEY_new())
let n = try ArbitraryPrecisionInteger(bytes: n)
let e = try ArbitraryPrecisionInteger(bytes: e)
@@ -163,6 +163,85 @@ final class CBCTests: XCTestCase {
}
}
func testDecryptRejectsPaddingLengthGreaterThanBlockSize() throws {
// A plaintext whose final block claims a PKCS#7 pad length of 17 (0x11)
// is invalid for a 16-byte block: the maximum valid PKCS#7 pad is one
// full block (16). Correct unpadding must reject it. Regression guard:
// the previous `trimPadding` accepted any pad length up to 255 and
// scanned across blocks, so it wrongly stripped 17 bytes here.
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// 32-byte (block-multiple) plaintext ending in 17 bytes of 0x11.
var plaintext = Data(repeating: 0xAB, count: 15)
plaintext.append(Data(repeating: 0x11, count: 17))
precondition(plaintext.count == 32)
let ciphertext = try AES._CBC.encrypt(plaintext, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
) { error in
guard let error = error as? CryptoKitError, case .incorrectParameterSize = error else {
XCTFail("Unexpected error: \(error)")
return
}
}
}
func testUnpadAcceptsAllValidPaddingLengths() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// For every valid PKCS#7 pad length (1...16), round-trip a message that
// pads to exactly that length and assert exact recovery.
for padLength in 1...16 {
let messageLength = 32 - padLength // pads to 32 bytes (two blocks)
let message = Data((0..<messageLength).map { UInt8(truncatingIfNeeded: $0) })
let ciphertext = try AES._CBC.encrypt(message, using: key, iv: iv, noPadding: false)
let decrypted = try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false)
XCTAssertEqual(decrypted, message, "round-trip failed for pad length \(padLength)")
}
}
func testUnpadRejectsCorruptedPaddingByte() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// Build a validly-padded block-multiple plaintext, then corrupt each
// padding byte except the last (which encodes the claimed length). The
// constant-time scan must reject a mismatch at any position.
for padLength in 2...16 {
var padded = Data((0..<(32 - padLength)).map { UInt8(truncatingIfNeeded: $0) })
padded.append(Data(repeating: UInt8(padLength), count: padLength))
precondition(padded.count == 32)
for position in (32 - padLength)..<31 {
var corrupted = padded
corrupted[position] = UInt8(padLength) ^ 0xFF // guaranteed != padLength
let ciphertext = try AES._CBC.encrypt(corrupted, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(
try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false),
"corruption at pad length \(padLength), position \(position) was not rejected"
)
}
}
}
func testUnpadRejectsZeroPaddingLength() throws {
let key = SymmetricKey(data: try Data(hexString: "b6fc08df9b778d11850356b8bfc9561a"))
let iv = try AES._CBC.IV(ivBytes: Array(hexString: "00000000000000000000000000000000"))
// A final byte of 0x00 claims a pad length of zero, which is invalid PKCS#7.
var padded = Data((0..<31).map { UInt8(truncatingIfNeeded: $0) })
padded.append(0x00)
let ciphertext = try AES._CBC.encrypt(padded, using: key, iv: iv, noPadding: true)
XCTAssertThrowsError(try AES._CBC.decrypt(ciphertext, using: key, iv: iv, noPadding: false))
}
func testToDataConversion() throws {
let randomBytes = (0..<16).map { _ in UInt8.random(in: UInt8.min...UInt8.max) }
let dataIn = Data(randomBytes)
@@ -910,6 +910,23 @@ final class TestRSASigning: XCTestCase {
return pemLines.joined(separator: "\n")
}
func test_invalidDERPublicKeyThrowsWithoutDoubleFree() throws {
// SEQUENCE { INTEGER 0, INTEGER 0 }
let badBase64 = "MAYCAQACAQ=="
let badDER = Array(Data(base64Encoded: badBase64)!)
XCTAssertThrowsError(try BoringSSLRSAPublicKey(derRepresentation: badDER))
}
func test_invalidPEMPublicKeyThrowsWithoutDoubleFree() throws {
// SEQUENCE { INTEGER 0, INTEGER 0 }
let badPEM = """
-----BEGIN PUBLIC KEY-----
MAYCAQACAQ==
-----END PUBLIC KEY-----
"""
XCTAssertThrowsError(try BoringSSLRSAPublicKey(pemRepresentation: badPEM))
}
}