Compare commits

..
3 Commits
Author SHA1 Message Date
Evan Wilde 33a20e650c Set CRYPTO_IN_SWIFTPM (#177)
Needed to expose SecureEncalve through SwiftCrypto when building for
Swift-Certificates. CRYPTO_IN_SWIFTPM is set all of the time in
package.swift, while CRYPTO_IN_SWIFTPM_FORCE_BUILD_API is only set in
development. Lets enable the one that's on all of the time, and remove
the one that isn't so that we get our declarations.
2023-04-19 06:40:30 +01:00
Brandon 65f8c60ab3 ChaCha20 CTR Encryption (#169)
* OpenSSLChaCha20CTR Implementation. Wraps CCryptoBoringSSL_CRYPTO_chacha_20.

* Insecure extension implementing the ChaCha20 CTR encrypt method.

* Added ChaCha20CTR Tests based on vectors provided in RFC9001 Appendix A.5

* Corrected year in header

* Changed return type to Data. Removed redundant pointer castings. Removed unnecessary array allocations in favor of withUnsafeBytes.

* Introduced a typed ChaCha20CTR Nonce and Counter struct in order to help enforce parameter constraints and type safety.

* Formatting

* Updated tests to use new Nonce and Counter structs. Added additional test checking for invalid parameters.

* Switch to HexStrings for better readability.

* Removed empty line at top of file

* Fixed UInt32.max counter assertion.

* Moved the bindMemory calls out of the function and copied a note from a similar situation elsewhere in the codebase.

* Formatting

* Implemented an _encryptContiguous function that prevents having to use the withContiguousStorageIfAvailable method. If our DataProtocol is contiguous we encrypt directly, otherwise we consolidate before encrypting. Removed inLen param from chacha20CTR call.

* Replaced the chacha20CTR function with a direct call to CCryptoBoringSSL_CRYPTO_chacha_20.

* Counter is now backed by a UInt32 instead of Data. Removed Sequence conformance.

* Formatting

* Formatting

* Replaced unsafe code (unsafeBytes and load) with a more generic and safer UInt32 construction.

* Replaced counterAsUInt32 definitions with integer literals to avoid symmetric bugs in the load.

* Updated _CryptoExtras/CMakeList.txt
2023-04-18 10:06:55 +01:00
Cory Benfield 1863cc9dcf Drop support for Swift 5.5 (#172)
* Drop support for Swift 5.5

This patch drops support for Swift 5.5.

* Drop LinuxMain.swift
2023-04-13 16:46:47 +01:00
9 changed files with 292 additions and 39 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
// swift-tools-version:5.5
// swift-tools-version:5.6
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
+3 -2
View File
@@ -108,13 +108,14 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
### Swift versions
The most recent versions of Swift Crypto support Swift 5.5 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
The most recent versions of Swift Crypto support Swift 5.6 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
Swift Crypto | Minimum Swift Version
------------------|----------------------
`2.0.0 ..< 2.1.0` | 5.2
`2.1.0 ..< 2.2.0` | 5.4
`2.2.0 ...` | 5.5
`2.2.0 ..< 2.4.2` | 5.5
`2.4.2 ...` | 5.6
### Compatibility
+1 -1
View File
@@ -82,7 +82,7 @@ add_library(Crypto
"Util/Zeroization.swift")
target_compile_definitions(Crypto PRIVATE
CRYPTO_IN_SWIFTPM_FORCE_BUILD_API)
"$<$<COMPILE_LANGUAGE:Swift>:CRYPTO_IN_SWIFTPM>")
target_include_directories(Crypto PRIVATE
$<TARGET_PROPERTY:CCryptoBoringSSL,INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:CCryptoBoringSSLShims,INCLUDE_DIRECTORIES>
+2
View File
@@ -13,6 +13,8 @@
##===----------------------------------------------------------------------===##
add_library(_CryptoExtras
"ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift"
"ChaCha20CTR/ChaCha20CTR.swift"
"RSA/RSA.swift"
"RSA/RSA_boring.swift"
"RSA/RSA_security.swift"
@@ -0,0 +1,68 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
import Crypto
@_implementationOnly import CryptoBoringWrapper
import Foundation
enum OpenSSLChaCha20CTRImpl {
static func encrypt<M: DataProtocol, N: ContiguousBytes>(key: SymmetricKey, message: M, counter: UInt32, nonce: N) throws -> Data {
guard key.bitCount == Insecure.ChaCha20CTR.keyBitsCount else {
throw CryptoKitError.incorrectKeySize
}
// If our message, conforming to DataProtocol, happens to be allocated contiguously in memory, then we can grab the first, and only, contiguous region and operate on it
if message.regions.count == 1 {
return self._encryptContiguous(key: key, message: message.regions.first!, counter: counter, nonce: nonce)
} else {
// Otherwise we need to consolidate the noncontiguous bytes by instantiating an Array<UInt8>
let contiguousMessage = Array(message)
return self._encryptContiguous(key: key, message: contiguousMessage, counter: counter, nonce: nonce)
}
}
/// A fast-path for encrypting contiguous data. Also inlinable to gain specialization information.
@inlinable
static func _encryptContiguous<Plaintext: ContiguousBytes, Nonce: ContiguousBytes>(key: SymmetricKey, message: Plaintext, counter: UInt32, nonce: Nonce) -> Data {
key.withUnsafeBytes { keyPtr in
nonce.withUnsafeBytes { noncePtr in
message.withUnsafeBytes { plaintextPtr in
// We bind all three pointers here. These binds are not technically safe, but because we
// know the pointers don't persist they can't violate the aliasing rules. We really
// want a "with memory rebound" function but we don't have it yet.
let keyBytes = keyPtr.bindMemory(to: UInt8.self)
let nonceBytes = noncePtr.bindMemory(to: UInt8.self)
let plaintext = plaintextPtr.bindMemory(to: UInt8.self)
var ciphertext = Data(repeating: 0, count: plaintext.count)
ciphertext.withUnsafeMutableBytes { ciphertext in
CCryptoBoringSSL_CRYPTO_chacha_20(
ciphertext,
plaintext.baseAddress,
plaintext.count,
keyBytes.baseAddress,
nonceBytes.baseAddress,
counter
)
}
return ciphertext
}
}
}
}
}
@@ -0,0 +1,118 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
import Crypto
@_implementationOnly import CryptoBoringWrapper
import Foundation
typealias ChaCha20CTRImpl = OpenSSLChaCha20CTRImpl
extension Insecure {
/// ChaCha20-CTR with 96-bit nonces and a 32 bit counter.
public enum ChaCha20CTR {
static let keyBitsCount = 256
static let nonceByteCount = 12
static let counterByteCount = 4
/// Encrypts data using ChaCha20CTR
///
/// - Parameters:
/// - message: The message to encrypt
/// - key: A 256-bit encryption key
/// - counter: A 4 byte counter (UInt32), defaults to 0
/// - nonce: A 12 byte nonce for ChaCha20 encryption. The nonce must be unique for every use of the key to seal data.
/// - Returns: The encrypted ciphertext
/// - Throws: CipherError errors
/// - Warning: You most likely want to use the ChaChaPoly implemention with AuthenticatedData available at `Crypto.ChaChaPoly`
public static func encrypt<
Plaintext: DataProtocol
>(
_ message: Plaintext,
using key: SymmetricKey,
counter: Insecure.ChaCha20CTR.Counter = Counter(),
nonce: Insecure.ChaCha20CTR.Nonce
) throws -> Data {
return try ChaCha20CTRImpl.encrypt(key: key, message: message, counter: counter.counter, nonce: nonce.bytes)
}
}
}
extension Insecure.ChaCha20CTR {
public struct Nonce: ContiguousBytes, Sequence {
let bytes: Data
/// Generates a fresh random Nonce. Unless required by a specification to provide a specific Nonce, this is the recommended initializer.
public init() {
var data = Data(repeating: 0, count: Insecure.ChaCha20CTR.nonceByteCount)
data.withUnsafeMutableBytes {
assert($0.count == Insecure.ChaCha20CTR.nonceByteCount)
$0.initializeWithRandomBytes(count: Insecure.ChaCha20CTR.nonceByteCount)
}
self.bytes = data
}
public init<D: DataProtocol>(data: D) throws {
if data.count != Insecure.ChaCha20CTR.nonceByteCount {
throw CryptoKitError.incorrectParameterSize
}
self.bytes = Data(data)
}
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
public func makeIterator() -> Array<UInt8>.Iterator {
self.withUnsafeBytes({ buffPtr in
Array(buffPtr).makeIterator()
})
}
}
public struct Counter: ContiguousBytes {
let counter: UInt32
/// Generates a fresh Counter set to 0. Unless required by a specification to provide a specific Counter, this is the recommended initializer.
public init() {
self.counter = 0
}
/// Explicitly set the Counter's offset using a byte sequence
public init<D: DataProtocol>(data: D) throws {
if data.count != Insecure.ChaCha20CTR.counterByteCount {
throw CryptoKitError.incorrectParameterSize
}
let startIndex = data.startIndex
self.counter = (
(UInt32(data[data.index(startIndex, offsetBy: 0)]) << 0) |
(UInt32(data[data.index(startIndex, offsetBy: 1)]) << 8) |
(UInt32(data[data.index(startIndex, offsetBy: 2)]) << 16) |
(UInt32(data[data.index(startIndex, offsetBy: 3)]) << 24)
)
}
/// Explicitly set the Counter's offset using a UInt32
public init(offset: UInt32) throws {
self.counter = offset
}
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try Swift.withUnsafeBytes(of: self.counter, body)
}
}
}
-14
View File
@@ -1,14 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
fatalError("Please use --enable-test-discovery to run the tests instead")
@@ -0,0 +1,99 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
import Crypto
import _CryptoExtras
class ChaCha20CTRTests: XCTestCase {
/// Test Vector - https://datatracker.ietf.org/doc/html/rfc9001#name-chacha20-poly1305-short-hea
func testChaCha20CTR_v1() throws {
let hpKey = try Array(hexString: "25a282b9e82f06f21f488917a4fc8f1b73573685608597d0efcb076b0ab7a7a4")
/// Sample = 0x5e5cd55c41f69080575d7999c25a5bfb
let counterAsData = try Array(hexString: "5e5cd55c")
let counterAsUInt32 = UInt32(bigEndian: 0x5e5cd55c)
let iv = try Array(hexString: "41f69080575d7999c25a5bfb")
let mask: Data = try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: SymmetricKey(data: hpKey), counter: Insecure.ChaCha20CTR.Counter(data: counterAsData), nonce: Insecure.ChaCha20CTR.Nonce(data: iv))
let mask2: Data = try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: SymmetricKey(data: hpKey), counter: Insecure.ChaCha20CTR.Counter(offset: counterAsUInt32), nonce: Insecure.ChaCha20CTR.Nonce(data: iv))
XCTAssertEqual(mask, try Data(hexString: "aefefe7d03"))
XCTAssertEqual(mask, mask2)
}
/// Test Vector - https://www.ietf.org/archive/id/draft-ietf-quic-v2-10.html#name-chacha20-poly1305-short-head
func testChaCha20CTR_v2() throws {
let hpKey = try Array(hexString: "d659760d2ba434a226fd37b35c69e2da8211d10c4f12538787d65645d5d1b8e2")
/// Sample = 0xe7b6b932bc27d786f4bc2bb20f2162ba
let counterAsData = try Array(hexString: "e7b6b932")
let counterAsUInt32 = UInt32(bigEndian: 0xe7b6b932)
let iv = try Array(hexString: "bc27d786f4bc2bb20f2162ba")
let mask: Data = try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: SymmetricKey(data: hpKey), counter: Insecure.ChaCha20CTR.Counter(data: counterAsData), nonce: Insecure.ChaCha20CTR.Nonce(data: iv))
let mask2: Data = try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: SymmetricKey(data: hpKey), counter: Insecure.ChaCha20CTR.Counter(offset: counterAsUInt32), nonce: Insecure.ChaCha20CTR.Nonce(data: iv))
XCTAssertEqual(mask, try Data(hexString: "97580e32bf"))
XCTAssertEqual(mask, mask2)
}
func testChaCha20CTR_InvalidParameters() throws {
let keyTooLong: SymmetricKey = SymmetricKey(data: [214, 89, 118, 13, 43, 164, 52, 162, 38, 253, 55, 179, 92, 105, 226, 218, 130, 17, 209, 12, 79, 18, 83, 135, 135, 214, 86, 69, 213, 209, 184, 226, 22])
XCTAssertThrowsError(try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: keyTooLong, nonce: Insecure.ChaCha20CTR.Nonce())) { error in
guard case CryptoKitError.incorrectKeySize = error else { return XCTFail("Error thrown was of unexpected type: \(error)") }
}
let keyTooShort: SymmetricKey = SymmetricKey(data: [214, 89, 118, 13, 43, 164, 52, 162, 38, 253, 55, 179, 92, 105, 226, 218, 130, 17, 209, 12, 79, 18, 83, 135, 135, 214, 86, 69, 213, 209, 184])
XCTAssertThrowsError(try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: keyTooShort, nonce: Insecure.ChaCha20CTR.Nonce())) { error in
guard case CryptoKitError.incorrectKeySize = error else { return XCTFail("Error thrown was of unexpected type: \(error)") }
}
let nonceTooLong: [UInt8] = [188, 39, 215, 134, 244, 188, 43, 178, 15, 33, 98, 186, 14]
XCTAssertThrowsError(try Insecure.ChaCha20CTR.Nonce(data: nonceTooLong)) { error in
guard case CryptoKitError.incorrectParameterSize = error else { return XCTFail("Error thrown was of unexpected type: \(error)") }
}
let nonceTooShort: [UInt8] = [188, 39, 215, 134, 244, 188, 43, 178, 15, 33, 98]
XCTAssertThrowsError(try Insecure.ChaCha20CTR.Nonce(data: nonceTooShort)) { error in
guard case CryptoKitError.incorrectParameterSize = error else { return XCTFail("Error thrown was of unexpected type: \(error)") }
}
let counterTooLong: [UInt8] = [231, 182, 185, 50, 82]
XCTAssertThrowsError(try Insecure.ChaCha20CTR.Counter(data: counterTooLong)) { error in
guard case CryptoKitError.incorrectParameterSize = error else { return XCTFail("Error thrown was of unexpected type: \(error)") }
}
let counterTooShort: [UInt8] = [231, 182, 185]
XCTAssertThrowsError(try Insecure.ChaCha20CTR.Counter(data: counterTooShort)) { error in
guard case CryptoKitError.incorrectParameterSize = error else { return XCTFail("Error thrown was of unexpected type: \(error)") }
}
let key: SymmetricKey = SymmetricKey(data: [214, 89, 118, 13, 43, 164, 52, 162, 38, 253, 55, 179, 92, 105, 226, 218, 130, 17, 209, 12, 79, 18, 83, 135, 135, 214, 86, 69, 213, 209, 184, 226])
// Ensure UInt32.max Counter Supported
XCTAssertNoThrow(try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: key, counter: Insecure.ChaCha20CTR.Counter(offset: UInt32.max), nonce: Insecure.ChaCha20CTR.Nonce()))
// Assert that two calls with the same Counter + Nonce params results in the same output
let nonce = Insecure.ChaCha20CTR.Nonce()
let counter = Insecure.ChaCha20CTR.Counter()
let ciphertext1 = try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: key, counter: counter, nonce: nonce)
let ciphertext2 = try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: key, counter: counter, nonce: nonce)
XCTAssertEqual(ciphertext1, ciphertext2)
// Assert that two calls with different Nonce params results in different output
let ciphertext3 = try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: key, counter: counter, nonce: Insecure.ChaCha20CTR.Nonce())
let ciphertext4 = try Insecure.ChaCha20CTR.encrypt(Array<UInt8>(repeating: 0, count: 5), using: key, counter: counter, nonce: Insecure.ChaCha20CTR.Nonce())
XCTAssertNotEqual(ciphertext3, ciphertext4)
}
}
-21
View File
@@ -1,21 +0,0 @@
version: "3"
services:
runtime-setup:
image: swift-crypto:20.04-5.5
build:
args:
ubuntu_version: "focal"
swift_version: "5.5"
test:
image: swift-crypto:20.04-5.5
environment: []
#- SANITIZER_ARG=--sanitize=thread
cmake:
image: swift-crypto:20.04-5.5
shell:
image: swift-crypto:20.04-5.5