diff --git a/Sources/CryptoExtras/AES/AES_CBC.swift b/Sources/CryptoExtras/AES/AES_CBC.swift index f94910bf..77ffa823 100644 --- a/Sources/CryptoExtras/AES/AES_CBC.swift +++ b/Sources/CryptoExtras/AES/AES_CBC.swift @@ -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: 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: 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(_ 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)) } } diff --git a/Sources/CryptoExtras/AES/Block Function.swift b/Sources/CryptoExtras/AES/Block Function.swift index 0bf0ccbc..ea3173f2 100644 --- a/Sources/CryptoExtras/AES/Block Function.swift +++ b/Sources/CryptoExtras/AES/Block Function.swift @@ -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: 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(_ body: (UnsafeRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType { - return try Swift.withUnsafeBytes(of: self.blockBytes, body) - } - mutating func withUnsafeMutableBytes(_ 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.. 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( - _ body: (UnsafeBufferPointer) 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( - _ body: (inout UnsafeMutableBufferPointer) 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) - } - } -} diff --git a/Sources/CryptoExtras/AES/BoringSSL/AES_CBC_boring.swift b/Sources/CryptoExtras/AES/BoringSSL/AES_CBC_boring.swift new file mode 100644 index 00000000..6efecd84 --- /dev/null +++ b/Sources/CryptoExtras/AES/BoringSSL/AES_CBC_boring.swift @@ -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: 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: 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) +} diff --git a/Sources/CryptoExtras/CMakeLists.txt b/Sources/CryptoExtras/CMakeLists.txt index e9a74327..9ae79fe0 100644 --- a/Sources/CryptoExtras/CMakeLists.txt +++ b/Sources/CryptoExtras/CMakeLists.txt @@ -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" diff --git a/Tests/CryptoExtrasTests/AES_CBCTests.swift b/Tests/CryptoExtrasTests/AES_CBCTests.swift index 11fa7ec4..9df963c7 100644 --- a/Tests/CryptoExtrasTests/AES_CBCTests.swift +++ b/Tests/CryptoExtrasTests/AES_CBCTests.swift @@ -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..