diff --git a/Sources/NIOSSL/CustomPrivateKey.swift b/Sources/NIOSSL/CustomPrivateKey.swift new file mode 100644 index 00000000..d89654ee --- /dev/null +++ b/Sources/NIOSSL/CustomPrivateKey.swift @@ -0,0 +1,278 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIOCore +@_implementationOnly import CNIOBoringSSL + +/// `NIOSSLCustomPrivateKey` defines the interface of a custom, non-BoringSSL private key. +/// +/// In a number of circumstances it is advantageous to store a TLS private key in some form of high-security storage, +/// such as a smart card. In these cases it is not possible to represent the TLS private key directly as a sequence +/// of bytes that BoringSSL will understand. +/// +/// This protocol allows a type to implement callbacks that perform the specific operation required by the TLS handshake. +/// Implementers are required to specify what signature algorithms they support, and then must implement **only one** of +/// the `sign`/`decrypt` functions. For elliptic curve keys, implementers should implement `sign`. For RSA keys, +/// implementers should implement `sign` and, if supporting RSA key exchange in TLS versions before 1.3, you should +/// also implement `decrypt`. +/// +/// If the same `NIOSSLCustomPrivateKey` implementation is used by multiple channels at once, then no synchronization +/// is imposed by SwiftNIO. The calls to the protocol requirements will be made on event loop threads, so if further +/// synchronization is required it is up to the implementer to provide it. Note that it is unacceptable to block in +/// these functions, and so potentially blocking operations must delegate to another thread. +public protocol NIOSSLCustomPrivateKey { + /// The signature algorithms supported by this key. + var signatureAlgorithms: [SignatureAlgorithm] { get } + + /// Called to perform a signing operation. + /// + /// The data being passed to the call has not been hashed, and it is the responsibility of the implementer + /// to ensure that the data _is_ hashed before use. `algorithm` will control what hash algorithm should be used. + /// This call will always execute on `channel.eventLoop`. + /// + /// This function should be implemented by both EC and RSA keys. + /// + /// - parameters: + /// - channel: The `Channel` representing the connection for which we are performing the signing operation. + /// - algorithm: The `SignatureAlgorithm` that should be used to generate the signature. + /// - data: The data to be signed. + /// - returns: An `EventLoopFuture` that will be fulfilled with a `ByteBuffer` containing the signature bytes, if + /// the signing operation completes, or that will be failed with a relevant `Error` if the signature could not + /// be produced. + func sign(channel: Channel, algorithm: SignatureAlgorithm, data: ByteBuffer) -> EventLoopFuture + + /// Called to perform a decryption operation. + /// + /// The data being passed to the call should be decrypted using _raw_ RSA public key decryption, without padding. + /// This call will always execute on `channel.eventLoop`. + /// + /// This function should only be implemented for RSA keys, and then only if you support RSA key exchange. If you + /// are only using TLS 1.3 and later, this function is entirely unnecessary and it will never be called. + /// + /// - parameters: + /// - channel: The `Channel` representing the connection for which we are performing the decryption operation. + /// - data: The data to be decrypted. + /// - returns: An `EventLoopFuture` that will be fulfilled with a `ByteBuffer` containing the decrypted bytes, if + /// the decryption operation completes, or that will be failed with a relevant `Error` if the decrypted bytes + /// could not be produced. + func decrypt(channel: Channel, data: ByteBuffer) -> EventLoopFuture +} + +/// This is a type-erased wrapper that can be used to encapsulate a NIOSSLCustomPrivateKey and provide it with +/// hashability and equatability. +/// +/// While generally speaking type-erasure has some nasty performance problems, we only need the type-erasure for +/// Hashable conformance, which we don't use in any production code: only the tests use it. To that end, we don't +/// mind too much that we need to do this. +@usableFromInline +internal struct AnyNIOSSLCustomPrivateKey: NIOSSLCustomPrivateKey, Hashable { + @usableFromInline let _value: NIOSSLCustomPrivateKey + + @usableFromInline let _equalsFunction: (NIOSSLCustomPrivateKey) -> Bool + + @usableFromInline let _hashFunction: (inout Hasher) -> Void + + @inlinable init(_ key: CustomKey) { + self._value = key + self._equalsFunction = { ($0 as? CustomKey) == key } + self._hashFunction = { $0.combine(key) } + } + + // This method does not need to be @inlinable for performance, but it needs to be _at least_ + // @usableFromInline as it's a protocol requirement on a @usableFromInline type. + @inlinable var signatureAlgorithms: [SignatureAlgorithm] { + return self._value.signatureAlgorithms + } + + // This method does not need to be @inlinable for performance, but it needs to be _at least_ + // @usableFromInline as it's a protocol requirement on a @usableFromInline type. + @inlinable func sign(channel: Channel, algorithm: SignatureAlgorithm, data: ByteBuffer) -> EventLoopFuture { + return self._value.sign(channel: channel, algorithm: algorithm, data: data) + } + + // This method does not need to be @inlinable for performance, but it needs to be _at least_ + // @usableFromInline as it's a protocol requirement on a @usableFromInline type. + @inlinable func decrypt(channel: Channel, data: ByteBuffer) -> EventLoopFuture { + return self._value.decrypt(channel: channel, data: data) + } + + // This method does not need to be @inlinable for performance, but it needs to be _at least_ + // @usableFromInline as it's a protocol requirement on a @usableFromInline type. + @inlinable func hash(into hasher: inout Hasher) { + self._hashFunction(&hasher) + } + + // This method does not need to be @inlinable for performance, but it needs to be _at least_ + // @usableFromInline as it's a protocol requirement on a @usableFromInline type. + @inlinable static func ==(lhs: AnyNIOSSLCustomPrivateKey, rhs: AnyNIOSSLCustomPrivateKey) -> Bool { + return lhs._equalsFunction(rhs._value) + } +} + +extension SSLConnection { + fileprivate var customKey: NIOSSLCustomPrivateKey? { + guard case .some(.privateKey(let key)) = self.parentContext.configuration.privateKey, + case .custom(let customKey) = key.representation else { + return nil + } + + return customKey + } + + fileprivate func customPrivateKeySign( + signatureAlgorithm: UInt16, + in: UnsafeBufferPointer + ) -> ssl_private_key_result_t { + precondition(self.customPrivateKeyResult == nil) + + guard let customKey = self.customKey else { + preconditionFailure() + } + + let wrappedAlgorithm = SignatureAlgorithm(rawValue: signatureAlgorithm) + guard customKey.signatureAlgorithms.contains(wrappedAlgorithm) else { + return ssl_private_key_failure + } + + // This force-unwrap pair is safe: we can only handshake while we're in a pipeline. + let channel = self.parentHandler!.channel! + var inputBytes = channel.allocator.buffer(capacity: `in`.count) + inputBytes.writeBytes(`in`) + + let result = customKey.sign(channel: channel, algorithm: wrappedAlgorithm, data: inputBytes) + result.whenComplete { signingResult in + self.storeCustomPrivateKeyResult(signingResult, channel: channel) + } + + return ssl_private_key_retry + } + + fileprivate func customPrivateKeyDecrypt( + in: UnsafeBufferPointer + ) -> ssl_private_key_result_t { + precondition(self.customPrivateKeyResult == nil) + + guard let customKey = self.customKey else { + preconditionFailure() + } + + // This force-unwrap pair is safe: we can only handshake while we're in a pipeline. + let channel = self.parentHandler!.channel! + var inputBytes = channel.allocator.buffer(capacity: `in`.count) + inputBytes.writeBytes(`in`) + + let result = customKey.decrypt(channel: channel, data: inputBytes) + result.whenComplete { decryptionResult in + self.storeCustomPrivateKeyResult(decryptionResult, channel: channel) + } + + return ssl_private_key_retry + } + + fileprivate func customPrivateKeyComplete(out: inout UnsafeMutableBufferPointer) -> ssl_private_key_result_t { + switch self.customPrivateKeyResult { + case .none: + return ssl_private_key_retry + case .some(.failure): + return ssl_private_key_failure + case .some(.success(let signingResult)): + guard signingResult.readableBytes <= out.count else { + return ssl_private_key_failure + } + + let (_, lastIndex) = out.initialize(from: signingResult.readableBytesView) + out = UnsafeMutableBufferPointer(rebasing: out[.., channel: Channel) { + // When we complete here we need to set our result state, and then ask to respin the handshake. + // If we can't respin the handshake because we've dropped the parent handler, that's fine, no harm no foul. + // For that reason, we tolerate both the verify manager and the parent handler being nil. + channel.eventLoop.execute { + precondition(self.customPrivateKeyResult == nil) + self.customPrivateKeyResult = result + self.parentHandler?.resumeHandshake() + } + } +} + +// We heap-allocate the SSL_PRIVATE_KEY_METHOD we need because we can't define a static stored property with fixed address +// in Swift. +internal let customPrivateKeyMethod: UnsafePointer = { + let pointer = UnsafeMutablePointer.allocate(capacity: 1) + pointer.pointee = .init(sign: customKeySign, decrypt: customKeyDecrypt, complete: customKeyComplete) + return UnsafePointer(pointer) +}() + +/// This is our entry point from BoringSSL when we've been asked to do a sign. +fileprivate func customKeySign( + ssl: OpaquePointer?, out: UnsafeMutablePointer?, outLen: UnsafeMutablePointer?, + maxOut: size_t, signatureAlgorithm: UInt16, in: UnsafePointer?, inLen: Int +) -> ssl_private_key_result_t { + guard let ssl = ssl, out != nil, let outLen = outLen, let `in` = `in` else { + preconditionFailure() + } + + let connection = SSLConnection.loadConnectionFromSSL(ssl) + let inBuffer = UnsafeBufferPointer(start: `in`, count: inLen) + + // We never return anything here. + outLen.pointee = 0 + + return connection.customPrivateKeySign(signatureAlgorithm: signatureAlgorithm, in: inBuffer) +} + +/// This is our entry point from BoringSSL when we've been asked to do a decrypt. +fileprivate func customKeyDecrypt( + ssl: OpaquePointer?, out: UnsafeMutablePointer?, outLen: UnsafeMutablePointer?, + maxOut: Int, in: UnsafePointer?, inLen: Int +) -> ssl_private_key_result_t { + guard let ssl = ssl, out != nil, let outLen = outLen, let `in` = `in` else { + preconditionFailure() + } + + let connection = SSLConnection.loadConnectionFromSSL(ssl) + let inBuffer = UnsafeBufferPointer(start: `in`, count: inLen) + + // We never return anything here. + outLen.pointee = 0 + + return connection.customPrivateKeyDecrypt(in: inBuffer) +} + + +/// When BoringSSL is asking if we're done with our key operation, we come here. +fileprivate func customKeyComplete( + ssl: OpaquePointer?, out: UnsafeMutablePointer?, outLen: UnsafeMutablePointer?, + maxOut: Int +) -> ssl_private_key_result_t { + guard let ssl = ssl, let out = out, let outLen = outLen else { + preconditionFailure() + } + + let connection = SSLConnection.loadConnectionFromSSL(ssl) + var outBuffer = UnsafeMutableBufferPointer(start: out, count: maxOut) + let result = connection.customPrivateKeyComplete(out: &outBuffer) + + if result != ssl_private_key_success { + // We need to set outLen to zero here. + outLen.pointee = 0 + } else { + outLen.pointee = outBuffer.count + } + + return result +} diff --git a/Sources/NIOSSL/NIOSSLHandler.swift b/Sources/NIOSSL/NIOSSLHandler.swift index 9a4ce0c4..ed1ff782 100644 --- a/Sources/NIOSSL/NIOSSLHandler.swift +++ b/Sources/NIOSSL/NIOSSLHandler.swift @@ -49,6 +49,10 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo private var didDeliverData: Bool = false private var storedContext: ChannelHandlerContext? = nil private var shutdownTimeout: TimeAmount + + internal var channel: Channel? { + return self.storedContext?.channel + } internal init(connection: SSLConnection, shutdownTimeout: TimeAmount) { self.connection = connection @@ -251,7 +255,11 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo case .failed(let err): writeDataToNetwork(context: context, promise: nil) - // TODO(cory): This event should probably fire out of the BoringSSL info callback. + // If there's a failed private key operation, we fire both errors. + if case .failure(let privateKeyError) = self.connection.customPrivateKeyResult { + context.fireErrorCaught(privateKeyError) + } + context.fireErrorCaught(NIOSSLError.handshakeFailed(err)) channelClose(context: context, reason: NIOSSLError.handshakeFailed(err)) } @@ -710,7 +718,7 @@ fileprivate extension Array where Element == EventLoopPromise { // MARK:- Code for handling asynchronous handshake resumption. extension NIOSSLHandler { - internal func asynchronousCertificateVerificationComplete() { + internal func resumeHandshake() { guard let storedContext = self.storedContext else { // Oh well, the connection is dead. Do nothing. return diff --git a/Sources/NIOSSL/SSLCallbacks.swift b/Sources/NIOSSL/SSLCallbacks.swift index 773c0365..2d62b6ff 100644 --- a/Sources/NIOSSL/SSLCallbacks.swift +++ b/Sources/NIOSSL/SSLCallbacks.swift @@ -195,7 +195,7 @@ extension CustomVerifyManager { // escape the mutable ownership of self. precondition(connection.customVerificationManager == nil || connection.customVerificationManager?.result == .some(.pendingResult)) connection.customVerificationManager?.result = .complete(NIOSSLVerificationResult(result)) - connection.parentHandler?.asynchronousCertificateVerificationComplete() + connection.parentHandler?.resumeHandshake() } } diff --git a/Sources/NIOSSL/SSLConnection.swift b/Sources/NIOSSL/SSLConnection.swift index a391f8bf..8e198877 100644 --- a/Sources/NIOSSL/SSLConnection.swift +++ b/Sources/NIOSSL/SSLConnection.swift @@ -52,6 +52,7 @@ internal final class SSLConnection { /// Deprecated in favour of customVerificationManager private var verificationCallback: NIOSSLVerificationCallback? internal var customVerificationManager: CustomVerifyManager? + internal var customPrivateKeyResult: Result? /// Whether certificate hostnames should be validated. var validateHostnames: Bool { @@ -140,13 +141,7 @@ internal final class SSLConnection { guard let ssl = CNIOBoringSSL_X509_STORE_CTX_get_ex_data(storeContext, CNIOBoringSSL_SSL_get_ex_data_X509_STORE_CTX_idx()) else { preconditionFailure("Unable to obtain SSL * from X509_STORE_CTX * \(String(describing: storeContext))") } - guard let connectionPointer = CNIOBoringSSL_SSL_get_ex_data(OpaquePointer(ssl), sslConnectionExDataIndex) else { - // Uh-ok, our application state is gone. Don't let this error silently pass, go bang. - preconditionFailure("Unable to find application data from SSL * \(ssl), index \(sslConnectionExDataIndex)") - } - - // Grab a connection - let connection = Unmanaged.fromOpaque(connectionPointer).takeUnretainedValue() + let connection = SSLConnection.loadConnectionFromSSL(OpaquePointer(ssl)) switch connection.verificationCallback!(verificationResult, cert) { case .certificateVerified: return 1 @@ -172,12 +167,7 @@ internal final class SSLConnection { } // Ok, this call may be a resumption of a previous negotiation. We need to check if our connection object has a pre-existing verifiation state. - guard let connectionPointer = CNIOBoringSSL_SSL_get_ex_data(unwrappedSSL, sslConnectionExDataIndex) else { - // Uh-ok, our application state is gone. Don't let this error silently pass, go bang. - preconditionFailure("Unable to find application data from SSL * \(unwrappedSSL), index \(sslConnectionExDataIndex)") - } - - let connection = Unmanaged.fromOpaque(connectionPointer).takeUnretainedValue() + let connection = SSLConnection.loadConnectionFromSSL(unwrappedSSL) // We force unwrap the custom verification manager because for it to not be set is a programmer error. return connection.customVerificationManager!.process(on: connection) @@ -521,3 +511,16 @@ extension SSLConnection.PeerCertificateChainBuffers: RandomAccessCollection { return UnsafeRawBufferPointer(bufferDataPointer) } } + +// MARK: Helpers for managing ex_data +extension SSLConnection { + // Loads an SSLConnection from an SSL*. Does not take ownership of the pointer. + static func loadConnectionFromSSL(_ ssl: OpaquePointer) -> SSLConnection { + guard let connectionPointer = CNIOBoringSSL_SSL_get_ex_data(ssl, sslConnectionExDataIndex) else { + // Uh-ok, our application state is gone. Don't let this error silently pass, go bang. + preconditionFailure("Unable to find application data from SSL * \(ssl), index \(sslConnectionExDataIndex)") + } + + return Unmanaged.fromOpaque(connectionPointer).takeUnretainedValue() + } +} diff --git a/Sources/NIOSSL/SSLContext.swift b/Sources/NIOSSL/SSLContext.swift index b97132b6..75bf5e82 100644 --- a/Sources/NIOSSL/SSLContext.swift +++ b/Sources/NIOSSL/SSLContext.swift @@ -208,7 +208,7 @@ public final class NIOSSLContext { } // Configure signing algorithms - if let signingSignatureAlgorithms = configuration.signingSignatureAlgorithms { + if let signingSignatureAlgorithms = configuration.resolvedSigningSignatureAlgorithms { returnCode = signingSignatureAlgorithms .map { $0.rawValue } .withUnsafeBufferPointer { algo in @@ -378,8 +378,16 @@ extension NIOSSLContext { } private static func setPrivateKey(_ key: NIOSSLPrivateKey, context: OpaquePointer) throws { - guard 1 == CNIOBoringSSL_SSL_CTX_use_PrivateKey(context, key.ref) else { - throw NIOSSLError.failedToLoadPrivateKey + switch key.representation { + case .native: + let rc = key.withUnsafeMutableEVPPKEYPointer { ref in + CNIOBoringSSL_SSL_CTX_use_PrivateKey(context, ref) + } + guard 1 == rc else { + throw NIOSSLError.failedToLoadPrivateKey + } + case .custom: + CNIOBoringSSL_SSL_CTX_set_private_key_method(context, customPrivateKeyMethod) } } diff --git a/Sources/NIOSSL/SSLErrors.swift b/Sources/NIOSSL/SSLErrors.swift index 3c711dc0..1e5eac47 100644 --- a/Sources/NIOSSL/SSLErrors.swift +++ b/Sources/NIOSSL/SSLErrors.swift @@ -104,6 +104,10 @@ internal extension BoringSSLError { return .wantX509Lookup case SSL_ERROR_SYSCALL: return .syscallError + case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION: + // This is a terrible hack: we can't add cases to this enum, so we can't represent + // this directly. In all cases this should be the same as wantCertificateVerify, so we'll just use that. + return .wantCertificateVerify case SSL_ERROR_SSL: return .sslError(buildErrorStack()) default: diff --git a/Sources/NIOSSL/SSLPrivateKey.swift b/Sources/NIOSSL/SSLPrivateKey.swift index dfc4c315..c259125f 100644 --- a/Sources/NIOSSL/SSLPrivateKey.swift +++ b/Sources/NIOSSL/SSLPrivateKey.swift @@ -112,14 +112,25 @@ func globalBoringSSLPassphraseCallback(buf: UnsafeMutablePointer?, /// to obtain an in-memory representation of a key from a buffer of /// bytes or from a file path. public class NIOSSLPrivateKey { - internal let _ref: UnsafeMutableRawPointer /**/ + @usableFromInline + internal enum Representation { + case native(UnsafeMutableRawPointer /* { - return self._ref.assumingMemoryBound(to: EVP_PKEY.self) + @usableFromInline + internal let representation: Representation + + internal func withUnsafeMutableEVPPKEYPointer(_ body: (UnsafeMutablePointer) throws -> ReturnType) rethrows -> ReturnType { + guard case .native(let pointer) = self.representation else { + preconditionFailure() + } + + return try body(pointer.assumingMemoryBound(to: EVP_PKEY.self)) } private init(withReference ref: UnsafeMutablePointer) { - self._ref = UnsafeMutableRawPointer(ref) // erasing the type for @_implementationOnly import CNIOBoringSSL + self.representation = .native(UnsafeMutableRawPointer(ref)) // erasing the type for @_implementationOnly import CNIOBoringSSL } /// A delegating initializer for `init(file:format:passphraseCallback)` and `init(file:format:)`. @@ -266,6 +277,18 @@ public class NIOSSLPrivateKey { try self.init(bytes: bytes, format: format, callbackManager: manager) } + /// Create a `NIOSSLPrivateKey` from a custom private key callback. + /// + /// The private key, in addition to needing to conform to `NIOSSLCustomPrivateKey`, + /// is also required to be `Hashable`. This is because `NIOSSLPrivateKey`s are `Hashable`. + /// + /// - parameters: + /// - customPrivateKey: The custom private key to use with the TLS certificate. + @inlinable + public init(customPrivateKey: CustomKey) { + self.representation = .custom(AnyNIOSSLCustomPrivateKey(customPrivateKey)) + } + /// Create an NIOSSLPrivateKey wrapping a pointer into BoringSSL. /// /// This is a function that should be avoided as much as possible because it plays poorly with @@ -281,7 +304,13 @@ public class NIOSSLPrivateKey { } deinit { - CNIOBoringSSL_EVP_PKEY_free(self.ref) + switch self.representation { + case .native(let ref): + CNIOBoringSSL_EVP_PKEY_free(ref.assumingMemoryBound(to: EVP_PKEY.self)) + case .custom: + // Merely dropping the ref is enough. + () + } } } @@ -293,7 +322,9 @@ extension NIOSSLPrivateKey { /// X509 API in BoringSSL. /// /// The pointer provided to the closure is not valid beyond the lifetime of this method call. - private func withUnsafeDERBuffer(_ body: (UnsafeRawBufferPointer) throws -> T) throws -> T { + /// + /// This method is only safe to call on native private keys. + private static func withUnsafeDERBuffer(of ref: UnsafeMutablePointer, _ body: (UnsafeRawBufferPointer) throws -> T) throws -> T { guard let bio = CNIOBoringSSL_BIO_new(CNIOBoringSSL_BIO_s_mem()) else { fatalError("Failed to malloc for a BIO handler") } @@ -302,7 +333,7 @@ extension NIOSSLPrivateKey { CNIOBoringSSL_BIO_free(bio) } - let rc = CNIOBoringSSL_i2d_PrivateKey_bio(bio, self.ref) + let rc = CNIOBoringSSL_i2d_PrivateKey_bio(bio, ref) guard rc == 1 else { let errorStack = BoringSSLError.buildErrorStack() throw BoringSSLError.unknownError(errorStack) @@ -317,25 +348,57 @@ extension NIOSSLPrivateKey { return try body(bytes) } + + /// The custom signing algorithms required by this private key, if any. + /// + /// Is `nil` when the key is a native key, as this is handled by BoringSSL. + internal var customSigningAlgorithms: [SignatureAlgorithm]? { + switch self.representation { + case .native: + return nil + case .custom(let customKey): + return customKey.signatureAlgorithms + } + } } extension NIOSSLPrivateKey: Equatable { public static func ==(lhs: NIOSSLPrivateKey, rhs: NIOSSLPrivateKey) -> Bool { - // Annoyingly, EVP_PKEY_cmp does not have a traditional return value pattern. 1 means equal, 0 means non-equal, - // negative means error. Here we treat "error" as "not equal", because we have no error reporting mechanism from this call site, - // and anyway, BoringSSL considers "these keys aren't of the same type" to be an error, which is in my mind pretty ludicrous. - return CNIOBoringSSL_EVP_PKEY_cmp(lhs.ref, rhs.ref) == 1 + switch (lhs.representation, rhs.representation) { + case (.native, .native): + // Annoyingly, EVP_PKEY_cmp does not have a traditional return value pattern. 1 means equal, 0 means non-equal, + // negative means error. Here we treat "error" as "not equal", because we have no error reporting mechanism from this call site, + // and anyway, BoringSSL considers "these keys aren't of the same type" to be an error, which is in my mind pretty ludicrous. + return lhs.withUnsafeMutableEVPPKEYPointer { lhsRef in + rhs.withUnsafeMutableEVPPKEYPointer { rhsRef in + CNIOBoringSSL_EVP_PKEY_cmp(lhsRef, rhsRef) == 1 + } + } + + case (.custom(let lhsCustom), .custom(let rhsCustom)): + return lhsCustom == rhsCustom + + case (.native, .custom), (.custom, .native): + return false + } } } extension NIOSSLPrivateKey: Hashable { public func hash(into hasher: inout Hasher) { - // Sadly, BoringSSL doesn't provide us with a nice key hashing function. We therefore have only two options: - // we can either serialize the key into DER and feed that into the hasher, or we can attempt to hash the key parameters directly. - // We could attempt the latter, but frankly it causes a lot of pain for minimal gain, so we don't bother. This incurs an allocation, - // but that's ok. We crash if we hit an error here, as there is no way to recover. - try! self.withUnsafeDERBuffer { hasher.combine(bytes: $0) } + switch self.representation { + case .native(let ref): + // Sadly, BoringSSL doesn't provide us with a nice key hashing function. We therefore have only two options: + // we can either serialize the key into DER and feed that into the hasher, or we can attempt to hash the key parameters directly. + // We could attempt the latter, but frankly it causes a lot of pain for minimal gain, so we don't bother. This incurs an allocation, + // but that's ok. We crash if we hit an error here, as there is no way to recover. + hasher.combine(0) + try! NIOSSLPrivateKey.withUnsafeDERBuffer(of: ref.assumingMemoryBound(to: EVP_PKEY.self)) { hasher.combine(bytes: $0) } + case .custom(let custom): + hasher.combine(1) + custom.hash(into: &hasher) + } } } diff --git a/Sources/NIOSSL/TLSConfiguration.swift b/Sources/NIOSSL/TLSConfiguration.swift index ececb4b8..6f95a514 100644 --- a/Sources/NIOSSL/TLSConfiguration.swift +++ b/Sources/NIOSSL/TLSConfiguration.swift @@ -750,3 +750,53 @@ extension TLSConfiguration { additionalTrustRoots: additionalTrustRoots) } } + +extension TLSConfiguration { + /// Provides the resolved signature algorithms for signing, if any. + /// + /// Users can override the signature algorithms in two ways. Firstly, they can provide a + /// value for the `signingSignatureAlgorithms` field in the `TLSConfiguration` structure. + /// This acts as an artificial limiter, preventing certain algorithms from being used even + /// though a key might nominally support them. + /// + /// Secondly, users can provide a custom key. This custom key is only capable of using + /// certain signing algorithms. + /// + /// This property resolves these two into a single unified set by diffing them together. + /// If there is no override (i.e. a native key and no override of the + /// `signingSignatureAlgorithms` field then this returns `nil`. + internal var resolvedSigningSignatureAlgorithms: [SignatureAlgorithm]? { + switch (self.signingSignatureAlgorithms, self.privateKey?.customSigningAlgorithms) { + case (.none, .none): + // No overrides. + return nil + + case (.some(let manualOverrides), .none): + return manualOverrides + + case (.none, .some(let keyRequirements)): + return keyRequirements + + case (.some(let manualOverrides), .some(let keyRequirements)): + // Here we have to filter the set. We assume the two lists are small, and so we + // just use `Array.filter` instead of composing into a Set. Note that the order + // here is _semantic_: we have to filter the manual overrides array becuase + // that order was specified by the user, and we want to honor it. + return manualOverrides.filter { keyRequirements.contains($0) } + } + } +} + +extension NIOSSLPrivateKeySource { + /// The custom signing algorithms required by this private key, if any. + /// + /// Is `nil` when the key is a file-backed key, as this is handled by BoringSSL as a native key. + fileprivate var customSigningAlgorithms: [SignatureAlgorithm]? { + switch self { + case .file: + return nil + case .privateKey(let key): + return key.customSigningAlgorithms + } + } +} diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index a5bb76b9..207c0b76 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -37,6 +37,7 @@ class LinuxMainRunnerImpl: LinuxMainRunner { testCase(ByteBufferBIOTest.allTests), testCase(CertificateVerificationTests.allTests), testCase(ClientSNITests.allTests), + testCase(CustomPrivateKeyTests.allTests), testCase(IdentityVerificationTest.allTests), testCase(NIOSSLALPNTest.allTests), testCase(NIOSSLIntegrationTest.allTests), diff --git a/Tests/NIOSSLTests/CustomPrivateKeyTests+XCTest.swift b/Tests/NIOSSLTests/CustomPrivateKeyTests+XCTest.swift new file mode 100644 index 00000000..05ac23f5 --- /dev/null +++ b/Tests/NIOSSLTests/CustomPrivateKeyTests+XCTest.swift @@ -0,0 +1,43 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +// +// CustomPrivateKeyTests+XCTest.swift +// +import XCTest + +/// +/// NOTE: This file was generated by generate_linux_tests.rb +/// +/// Do NOT edit this file directly as it will be regenerated automatically when needed. +/// + +extension CustomPrivateKeyTests { + + @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") + static var allTests : [(String, (CustomPrivateKeyTests) -> () throws -> Void)] { + return [ + ("testHappyPathImmediateResultCustomECDSAKey", testHappyPathImmediateResultCustomECDSAKey), + ("testHappyPathImmediateResultCustomRSAKeyPSS", testHappyPathImmediateResultCustomRSAKeyPSS), + ("testHappyPathImmediateResultCustomRSAKeyPKCS1", testHappyPathImmediateResultCustomRSAKeyPKCS1), + ("testHappyPathDelayedResultCustomECDSAKey", testHappyPathDelayedResultCustomECDSAKey), + ("testHappyPathDelayedResultCustomRSAKeyPSS", testHappyPathDelayedResultCustomRSAKeyPSS), + ("testHappyPathDelayedResultCustomRSAKeyPKCS1", testHappyPathDelayedResultCustomRSAKeyPKCS1), + ("testMismatchedKeys", testMismatchedKeys), + ("testThrowingCustomErrorsSigning", testThrowingCustomErrorsSigning), + ("testKeyEquatability", testKeyEquatability), + ("testKeyHashability", testKeyHashability), + ] + } +} + diff --git a/Tests/NIOSSLTests/CustomPrivateKeyTests.swift b/Tests/NIOSSLTests/CustomPrivateKeyTests.swift new file mode 100644 index 00000000..6c95bae7 --- /dev/null +++ b/Tests/NIOSSLTests/CustomPrivateKeyTests.swift @@ -0,0 +1,658 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import XCTest +#if compiler(>=5.1) +@_implementationOnly import CNIOBoringSSL +#else +import CNIOBoringSSL +#endif +import NIOCore +import NIOEmbedded +import NIOConcurrencyHelpers +@testable import NIOSSL + +// This is a helper that lets us work with an EVP_PKEY. +fileprivate final class CustomPKEY { + private let ref: UnsafeMutablePointer + + init(from key: NIOSSLPrivateKey) { + // Extract a copy of the key reference here. + self.ref = key.withUnsafeMutableEVPPKEYPointer { pkey in + CNIOBoringSSL_EVP_PKEY_up_ref(pkey) + return pkey + } + } + + init(from generator: () -> UnsafeMutablePointer) { + self.ref = generator() + } + + deinit { + CNIOBoringSSL_EVP_PKEY_free(self.ref) + } + + func sign(algorithm: SignatureAlgorithm, data: ByteBuffer) -> ByteBuffer { + let ctx = CNIOBoringSSL_EVP_PKEY_CTX_new(self.ref, nil)! + defer { + CNIOBoringSSL_EVP_PKEY_CTX_free(ctx) + } + + // Step 1: We need to hash the input before we sign. + let hashContext = CNIOBoringSSL_EVP_MD_CTX_new()! + defer { + CNIOBoringSSL_EVP_MD_CTX_free(hashContext) + } + CNIOBoringSSL_EVP_MD_CTX_init(hashContext) + CNIOBoringSSL_EVP_DigestInit_ex(hashContext, algorithm.md, nil) + var rc = data.withUnsafeReadableBytes { bytesPtr in + CNIOBoringSSL_EVP_DigestUpdate(hashContext, bytesPtr.baseAddress?.assumingMemoryBound(to: UInt8.self), bytesPtr.count) + } + precondition(rc == 1) + + let signatureSize = CNIOBoringSSL_EVP_MD_size(algorithm.md) + + var digestBuffer = ByteBuffer() + digestBuffer.writeWithUnsafeMutableBytes(minimumWritableBytes: signatureSize) { outputPtr in + var actualSize = CUnsignedInt(outputPtr.count) + CNIOBoringSSL_EVP_DigestFinal_ex(hashContext, outputPtr.baseAddress?.assumingMemoryBound(to: UInt8.self), &actualSize) + return Int(actualSize) + } + + // Ok, great, we've hashed. Now let's do the signing. + precondition(CNIOBoringSSL_EVP_PKEY_sign_init(ctx) == 1) + // TODO: Add RSA padding when needed. + CNIOBoringSSL_EVP_PKEY_CTX_set_signature_md(ctx, algorithm.md) + + // For RSA algorithms we may need to add padding. + if let padding = algorithm.rsaPadding { + CNIOBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, padding) + } + + // And for some RSA padding, that may require a salt. + if let saltLength = algorithm.saltLen { + CNIOBoringSSL_EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, saltLength) + } + + // Now we find out the length we need. + var signatureLength: Int = 0 + rc = digestBuffer.withUnsafeReadableBytes { bytesPtr in + CNIOBoringSSL_EVP_PKEY_sign(ctx, nil, &signatureLength, bytesPtr.baseAddress?.assumingMemoryBound(to: UInt8.self), bytesPtr.count) + } + + precondition(rc == 1) + + // And finally we can do the sign. + var outputBuffer = ByteBuffer() + outputBuffer.writeWithUnsafeMutableBytes(minimumWritableBytes: signatureLength) { outputPtr in + precondition(signatureLength <= outputPtr.count) + let rc = digestBuffer.withUnsafeReadableBytes { bytesPtr in + CNIOBoringSSL_EVP_PKEY_sign(ctx, outputPtr.baseAddress?.assumingMemoryBound(to: UInt8.self), &signatureLength, bytesPtr.baseAddress?.assumingMemoryBound(to: UInt8.self), bytesPtr.count) + } + precondition(rc == 1) + return signatureLength + } + + return outputBuffer + } + + func decrypt(data: ByteBuffer) -> ByteBuffer { + // Decryption is only needed for RSA, so this has to work. + let rsa = CNIOBoringSSL_EVP_PKEY_get0_RSA(self.ref)! + let targetSize = CNIOBoringSSL_RSA_size(rsa) + + var output = ByteBuffer() + output.writeWithUnsafeMutableBytes(minimumWritableBytes: Int(targetSize)) { outputBytes in + var written = 0 + let rc = data.withUnsafeReadableBytes { inputBytes in + CNIOBoringSSL_RSA_decrypt( + rsa, + &written, + outputBytes.baseAddress?.assumingMemoryBound(to: UInt8.self), + outputBytes.count, + inputBytes.baseAddress?.assumingMemoryBound(to: UInt8.self), + inputBytes.count, + RSA_NO_PADDING + ) + } + precondition(rc == 1) + return written + } + + return output + } +} + +fileprivate final class CustomKeyImmediateResult: NIOSSLCustomPrivateKey, Hashable { + let backing: CustomPKEY + let signatureAlgorithms: [SignatureAlgorithm] + let expectedChannel: Channel + var signCallCount: Int + var decryptCallCount: Int + + fileprivate init(_ backing: CustomPKEY, signatureAlgorithms: [SignatureAlgorithm], expectedChannel: Channel) { + self.backing = backing + self.signatureAlgorithms = signatureAlgorithms + self.expectedChannel = expectedChannel + self.signCallCount = 0 + self.decryptCallCount = 0 + } + + func sign(channel: Channel, algorithm: SignatureAlgorithm, data: ByteBuffer) -> EventLoopFuture { + XCTAssertTrue(channel === self.expectedChannel) + XCTAssertTrue(self.signatureAlgorithms.contains(algorithm)) + self.signCallCount += 1 + return channel.eventLoop.makeSucceededFuture(self.backing.sign(algorithm: algorithm, data: data)) + } + + func decrypt(channel: Channel, data: ByteBuffer) -> EventLoopFuture { + XCTAssertTrue(channel === self.expectedChannel) + self.decryptCallCount += 1 + return channel.eventLoop.makeSucceededFuture(self.backing.decrypt(data: data)) + } + + static func ==(lhs: CustomKeyImmediateResult, rhs: CustomKeyImmediateResult) -> Bool { + return lhs.backing === rhs.backing && lhs.signatureAlgorithms == rhs.signatureAlgorithms + } + + func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self.backing)) + hasher.combine(signatureAlgorithms) + } +} + +fileprivate final class CustomKeyDelayedCompletion: NIOSSLCustomPrivateKey, Hashable { + let backing: CustomPKEY + let signatureAlgorithms: [SignatureAlgorithm] + let expectedChannel: Channel + var pendingSigningEvents: [EventLoopPromise] + var pendingDecryptionEvents: [EventLoopPromise] + + fileprivate init(_ backing: CustomPKEY, signatureAlgorithms: [SignatureAlgorithm], expectedChannel: Channel) { + self.backing = backing + self.signatureAlgorithms = signatureAlgorithms + self.expectedChannel = expectedChannel + self.pendingSigningEvents = [] + self.pendingDecryptionEvents = [] + } + + func sign(channel: Channel, algorithm: SignatureAlgorithm, data: ByteBuffer) -> EventLoopFuture { + XCTAssertTrue(channel === self.expectedChannel) + XCTAssertTrue(self.signatureAlgorithms.contains(algorithm)) + + let promise = channel.eventLoop.makePromise(of: Void.self) + self.pendingSigningEvents.append(promise) + return promise.futureResult.map { + self.backing.sign(algorithm: algorithm, data: data) + } + } + + func decrypt(channel: Channel, data: ByteBuffer) -> EventLoopFuture { + XCTAssertTrue(channel === self.expectedChannel) + + let promise = channel.eventLoop.makePromise(of: Void.self) + self.pendingDecryptionEvents.append(promise) + return promise.futureResult.map { + self.backing.decrypt(data: data) + } + } + + static func ==(lhs: CustomKeyDelayedCompletion, rhs: CustomKeyDelayedCompletion) -> Bool { + return lhs.backing === rhs.backing && lhs.signatureAlgorithms == rhs.signatureAlgorithms + } + + func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self.backing)) + hasher.combine(signatureAlgorithms) + } +} + +final class CustomPrivateKeyTests: XCTestCase { + fileprivate static let customECDSACertAndKey: (certificate: NIOSSLCertificate, key: CustomPKEY) = { + let (cert, originalKey) = generateSelfSignedCert(keygenFunction: { generateECPrivateKey(curveNID: NID_X9_62_prime256v1) }) + let derivedKey = CustomPKEY(from: originalKey) + return (certificate: cert, key: derivedKey) + }() + + fileprivate static let customRSACertAndKey: (certificate: NIOSSLCertificate, key: CustomPKEY) = { + let (cert, originalKey) = generateSelfSignedCert() + let derivedKey = CustomPKEY(from: originalKey) + return (certificate: cert, key: derivedKey) + }() + + private func configuredClientContext( + trustRoot: NIOSSLCertificate, + maxTLSVersion: TLSVersion? = nil, + cipherSuites: [NIOTLSCipher]? = nil + ) -> NIOSSLContext { + var config = TLSConfiguration.makeClientConfiguration() + config.trustRoots = .certificates([trustRoot]) + config.maximumTLSVersion = maxTLSVersion + if let cipherSuites = cipherSuites { + config.cipherSuiteValues = cipherSuites + } + return try! NIOSSLContext(configuration: config) + } + + private func configuredServerContext(certificate: NIOSSLCertificate, privateKey: NIOSSLPrivateKey) -> NIOSSLContext { + let config = TLSConfiguration.makeServerConfiguration( + certificateChain: [.certificate(certificate)], privateKey: .privateKey(privateKey) + ) + return try! NIOSSLContext(configuration: config) + } + + func testHappyPathImmediateResultCustomECDSAKey() throws { + let b2b = BackToBackEmbeddedChannel() + let happyPathKey = CustomKeyImmediateResult( + CustomPrivateKeyTests.customECDSACertAndKey.key, + signatureAlgorithms: [.ecdsaSecp256R1Sha256], + expectedChannel: b2b.server + ) + + let clientContext = self.configuredClientContext(trustRoot: CustomPrivateKeyTests.customECDSACertAndKey.certificate) + let serverContext = self.configuredServerContext( + certificate: CustomPrivateKeyTests.customECDSACertAndKey.certificate, + privateKey: NIOSSLPrivateKey(customPrivateKey: happyPathKey) + ) + XCTAssertNoThrow( + try b2b.client.pipeline.syncOperations.addHandlers( + [try NIOSSLClientHandler(context: clientContext, serverHostname: "localhost"), HandshakeCompletedHandler()] + ) + ) + XCTAssertNoThrow( + try b2b.server.pipeline.syncOperations.addHandlers( + [NIOSSLServerHandler(context: serverContext), HandshakeCompletedHandler()] + ) + ) + + XCTAssertNoThrow(try b2b.connectInMemory()) + XCTAssertEqual(happyPathKey.signCallCount, 1) + XCTAssertEqual(happyPathKey.decryptCallCount, 0) + XCTAssertTrue(b2b.client.handshakeSucceeded) + XCTAssertTrue(b2b.server.handshakeSucceeded) + } + + func testHappyPathImmediateResultCustomRSAKeyPSS() throws { + let b2b = BackToBackEmbeddedChannel() + let happyPathKey = CustomKeyImmediateResult( + CustomPrivateKeyTests.customRSACertAndKey.key, + signatureAlgorithms: [.rsaPssRsaeSha256], + expectedChannel: b2b.server + ) + + let clientContext = self.configuredClientContext(trustRoot: CustomPrivateKeyTests.customRSACertAndKey.certificate) + let serverContext = self.configuredServerContext( + certificate: CustomPrivateKeyTests.customRSACertAndKey.certificate, + privateKey: NIOSSLPrivateKey(customPrivateKey: happyPathKey) + ) + XCTAssertNoThrow( + try b2b.client.pipeline.syncOperations.addHandlers( + [try NIOSSLClientHandler(context: clientContext, serverHostname: "localhost"), HandshakeCompletedHandler()] + ) + ) + XCTAssertNoThrow( + try b2b.server.pipeline.syncOperations.addHandlers( + [NIOSSLServerHandler(context: serverContext), HandshakeCompletedHandler()] + ) + ) + + XCTAssertNoThrow(try b2b.connectInMemory()) + XCTAssertEqual(happyPathKey.signCallCount, 1) + XCTAssertEqual(happyPathKey.decryptCallCount, 0) + XCTAssertTrue(b2b.client.handshakeSucceeded) + XCTAssertTrue(b2b.server.handshakeSucceeded) + } + + func testHappyPathImmediateResultCustomRSAKeyPKCS1() throws { + let b2b = BackToBackEmbeddedChannel() + let happyPathKey = CustomKeyImmediateResult( + CustomPrivateKeyTests.customRSACertAndKey.key, + signatureAlgorithms: [.rsaPkcs1Sha256], + expectedChannel: b2b.server + ) + + // Rule out TLSv1.3, which doesn't support RSA decryption. + // We also want to force RSA key exchange, which will let us test the decrypt + // function. + let clientContext = self.configuredClientContext( + trustRoot: CustomPrivateKeyTests.customRSACertAndKey.certificate, + maxTLSVersion: .tlsv12, + cipherSuites: [.TLS_RSA_WITH_AES_128_GCM_SHA256] + ) + let serverContext = self.configuredServerContext( + certificate: CustomPrivateKeyTests.customRSACertAndKey.certificate, + privateKey: NIOSSLPrivateKey(customPrivateKey: happyPathKey) + ) + XCTAssertNoThrow( + try b2b.client.pipeline.syncOperations.addHandlers( + [try NIOSSLClientHandler(context: clientContext, serverHostname: "localhost"), HandshakeCompletedHandler()] + ) + ) + XCTAssertNoThrow( + try b2b.server.pipeline.syncOperations.addHandlers( + [NIOSSLServerHandler(context: serverContext), HandshakeCompletedHandler()] + ) + ) + + XCTAssertNoThrow(try b2b.connectInMemory()) + XCTAssertEqual(happyPathKey.signCallCount, 0) + XCTAssertEqual(happyPathKey.decryptCallCount, 1) + XCTAssertTrue(b2b.client.handshakeSucceeded) + XCTAssertTrue(b2b.server.handshakeSucceeded) + } + + func testHappyPathDelayedResultCustomECDSAKey() throws { + let b2b = BackToBackEmbeddedChannel() + let happyPathKey = CustomKeyDelayedCompletion( + CustomPrivateKeyTests.customECDSACertAndKey.key, + signatureAlgorithms: [.ecdsaSecp256R1Sha256], + expectedChannel: b2b.server + ) + + let clientContext = self.configuredClientContext(trustRoot: CustomPrivateKeyTests.customECDSACertAndKey.certificate) + let serverContext = self.configuredServerContext( + certificate: CustomPrivateKeyTests.customECDSACertAndKey.certificate, + privateKey: NIOSSLPrivateKey(customPrivateKey: happyPathKey) + ) + XCTAssertNoThrow( + try b2b.client.pipeline.syncOperations.addHandlers( + [try NIOSSLClientHandler(context: clientContext, serverHostname: "localhost"), HandshakeCompletedHandler()] + ) + ) + XCTAssertNoThrow( + try b2b.server.pipeline.syncOperations.addHandlers( + [NIOSSLServerHandler(context: serverContext), HandshakeCompletedHandler()] + ) + ) + + XCTAssertNoThrow(try b2b.connectInMemory()) + XCTAssertFalse(b2b.client.handshakeSucceeded) + XCTAssertFalse(b2b.server.handshakeSucceeded) + + // Complete the promise. + XCTAssertEqual(happyPathKey.pendingSigningEvents.count, 1) + XCTAssertEqual(happyPathKey.pendingDecryptionEvents.count, 0) + happyPathKey.pendingSigningEvents.first?.succeed(()) + + // Nothing happens until we start doing I/O again. + XCTAssertFalse(b2b.client.handshakeSucceeded) + XCTAssertFalse(b2b.server.handshakeSucceeded) + + XCTAssertNoThrow(try b2b.interactInMemory()) + XCTAssertTrue(b2b.client.handshakeSucceeded) + XCTAssertTrue(b2b.server.handshakeSucceeded) + } + + func testHappyPathDelayedResultCustomRSAKeyPSS() throws { + let b2b = BackToBackEmbeddedChannel() + let happyPathKey = CustomKeyDelayedCompletion( + CustomPrivateKeyTests.customRSACertAndKey.key, + signatureAlgorithms: [.rsaPssRsaeSha256], + expectedChannel: b2b.server + ) + + let clientContext = self.configuredClientContext(trustRoot: CustomPrivateKeyTests.customRSACertAndKey.certificate) + let serverContext = self.configuredServerContext( + certificate: CustomPrivateKeyTests.customRSACertAndKey.certificate, + privateKey: NIOSSLPrivateKey(customPrivateKey: happyPathKey) + ) + XCTAssertNoThrow( + try b2b.client.pipeline.syncOperations.addHandlers( + [try NIOSSLClientHandler(context: clientContext, serverHostname: "localhost"), HandshakeCompletedHandler()] + ) + ) + XCTAssertNoThrow( + try b2b.server.pipeline.syncOperations.addHandlers( + [NIOSSLServerHandler(context: serverContext), HandshakeCompletedHandler()] + ) + ) + + XCTAssertNoThrow(try b2b.connectInMemory()) + XCTAssertFalse(b2b.client.handshakeSucceeded) + XCTAssertFalse(b2b.server.handshakeSucceeded) + + // Complete the promise. + XCTAssertEqual(happyPathKey.pendingSigningEvents.count, 1) + XCTAssertEqual(happyPathKey.pendingDecryptionEvents.count, 0) + happyPathKey.pendingSigningEvents.first?.succeed(()) + + // Nothing happens until we start doing I/O again. + XCTAssertFalse(b2b.client.handshakeSucceeded) + XCTAssertFalse(b2b.server.handshakeSucceeded) + + XCTAssertNoThrow(try b2b.interactInMemory()) + XCTAssertTrue(b2b.client.handshakeSucceeded) + XCTAssertTrue(b2b.server.handshakeSucceeded) + } + + func testHappyPathDelayedResultCustomRSAKeyPKCS1() throws { + let b2b = BackToBackEmbeddedChannel() + let happyPathKey = CustomKeyDelayedCompletion( + CustomPrivateKeyTests.customRSACertAndKey.key, + signatureAlgorithms: [.rsaPkcs1Sha256], + expectedChannel: b2b.server + ) + + // Rule out TLSv1.3, which doesn't support RSA decryption. + // We also want to force RSA key exchange, which will let us test the decrypt + // function. + let clientContext = self.configuredClientContext( + trustRoot: CustomPrivateKeyTests.customRSACertAndKey.certificate, + maxTLSVersion: .tlsv12, + cipherSuites: [.TLS_RSA_WITH_AES_128_GCM_SHA256] + ) + let serverContext = self.configuredServerContext( + certificate: CustomPrivateKeyTests.customRSACertAndKey.certificate, + privateKey: NIOSSLPrivateKey(customPrivateKey: happyPathKey) + ) + XCTAssertNoThrow( + try b2b.client.pipeline.syncOperations.addHandlers( + [try NIOSSLClientHandler(context: clientContext, serverHostname: "localhost"), HandshakeCompletedHandler()] + ) + ) + XCTAssertNoThrow( + try b2b.server.pipeline.syncOperations.addHandlers( + [NIOSSLServerHandler(context: serverContext), HandshakeCompletedHandler()] + ) + ) + + XCTAssertNoThrow(try b2b.connectInMemory()) + XCTAssertFalse(b2b.client.handshakeSucceeded) + XCTAssertFalse(b2b.server.handshakeSucceeded) + + // Complete the promise. + XCTAssertEqual(happyPathKey.pendingSigningEvents.count, 0) + XCTAssertEqual(happyPathKey.pendingDecryptionEvents.count, 1) + happyPathKey.pendingDecryptionEvents.first?.succeed(()) + + // Nothing happens until we start doing I/O again. + XCTAssertFalse(b2b.client.handshakeSucceeded) + XCTAssertFalse(b2b.server.handshakeSucceeded) + + XCTAssertNoThrow(try b2b.interactInMemory()) + XCTAssertTrue(b2b.client.handshakeSucceeded) + XCTAssertTrue(b2b.server.handshakeSucceeded) + } + + func testMismatchedKeys() throws { + // We're going to generate another ECDSA key here, which we'll give to the backing code. + let alternativeKey = generateSelfSignedCert(keygenFunction: { generateECPrivateKey() }).1 + let b2b = BackToBackEmbeddedChannel() + let happyPathKey = CustomKeyImmediateResult( + CustomPKEY(from: alternativeKey), + signatureAlgorithms: [.ecdsaSecp256R1Sha256], + expectedChannel: b2b.server + ) + + let clientContext = self.configuredClientContext(trustRoot: CustomPrivateKeyTests.customECDSACertAndKey.certificate) + let serverContext = self.configuredServerContext( + certificate: CustomPrivateKeyTests.customECDSACertAndKey.certificate, + privateKey: NIOSSLPrivateKey(customPrivateKey: happyPathKey) + ) + XCTAssertNoThrow( + try b2b.client.pipeline.syncOperations.addHandler( + try NIOSSLClientHandler(context: clientContext, serverHostname: "localhost") + ) + ) + XCTAssertNoThrow( + try b2b.server.pipeline.syncOperations.addHandler( + NIOSSLServerHandler(context: serverContext) + ) + ) + + XCTAssertThrowsError(try b2b.connectInMemory()) + } + + func testThrowingCustomErrorsSigning() throws { + struct CustomError: Error { } + + let b2b = BackToBackEmbeddedChannel() + let happyPathKey = CustomKeyDelayedCompletion( + CustomPrivateKeyTests.customECDSACertAndKey.key, + signatureAlgorithms: [.ecdsaSecp256R1Sha256], + expectedChannel: b2b.server + ) + + let clientContext = self.configuredClientContext(trustRoot: CustomPrivateKeyTests.customECDSACertAndKey.certificate) + let serverContext = self.configuredServerContext( + certificate: CustomPrivateKeyTests.customECDSACertAndKey.certificate, + privateKey: NIOSSLPrivateKey(customPrivateKey: happyPathKey) + ) + XCTAssertNoThrow( + try b2b.client.pipeline.syncOperations.addHandler( + try NIOSSLClientHandler(context: clientContext, serverHostname: "localhost") + ) + ) + XCTAssertNoThrow( + try b2b.server.pipeline.syncOperations.addHandler( + NIOSSLServerHandler(context: serverContext) + ) + ) + + XCTAssertNoThrow(try b2b.connectInMemory()) + + // Complete the promise. + XCTAssertEqual(happyPathKey.pendingSigningEvents.count, 1) + XCTAssertEqual(happyPathKey.pendingDecryptionEvents.count, 0) + happyPathKey.pendingSigningEvents.first?.fail(CustomError()) + + XCTAssertThrowsError(try b2b.interactInMemory()) { error in + XCTAssertTrue(error is CustomError) + } + } + + func testKeyEquatability() throws { + let b2b = BackToBackEmbeddedChannel() + + let firstKey = CustomKeyDelayedCompletion( + CustomPrivateKeyTests.customECDSACertAndKey.key, + signatureAlgorithms: [.ecdsaSecp256R1Sha256], + expectedChannel: b2b.server + ) + + // Should be non-equal to first + let secondKey = CustomKeyDelayedCompletion( + CustomPrivateKeyTests.customECDSACertAndKey.key, + signatureAlgorithms: [.ecdsaSecp384R1Sha384], + expectedChannel: b2b.server + ) + + // Different object to first, but same equatable, so should be equal + let thirdKey = CustomKeyDelayedCompletion( + CustomPrivateKeyTests.customECDSACertAndKey.key, + signatureAlgorithms: [.ecdsaSecp256R1Sha256], + expectedChannel: b2b.server + ) + + XCTAssertEqual(firstKey, thirdKey) + XCTAssertNotEqual(firstKey, secondKey) + XCTAssertEqual(NIOSSLPrivateKey(customPrivateKey: firstKey), NIOSSLPrivateKey(customPrivateKey: thirdKey)) + XCTAssertNotEqual(NIOSSLPrivateKey(customPrivateKey: firstKey), NIOSSLPrivateKey(customPrivateKey: secondKey)) + } + + func testKeyHashability() throws { + let b2b = BackToBackEmbeddedChannel() + + let firstKey = CustomKeyDelayedCompletion( + CustomPrivateKeyTests.customECDSACertAndKey.key, + signatureAlgorithms: [.ecdsaSecp256R1Sha256], + expectedChannel: b2b.server + ) + + // Should hash non-equal to first + let secondKey = CustomKeyDelayedCompletion( + CustomPrivateKeyTests.customECDSACertAndKey.key, + signatureAlgorithms: [.ecdsaSecp384R1Sha384], + expectedChannel: b2b.server + ) + + // Different object to first, but same hashable, so should hash the same + let thirdKey = CustomKeyDelayedCompletion( + CustomPrivateKeyTests.customECDSACertAndKey.key, + signatureAlgorithms: [.ecdsaSecp256R1Sha256], + expectedChannel: b2b.server + ) + + XCTAssertEqual(Set([firstKey, secondKey]), Set([firstKey, secondKey, thirdKey])) + XCTAssertEqual( + Set([NIOSSLPrivateKey(customPrivateKey: firstKey), NIOSSLPrivateKey(customPrivateKey: secondKey)]), + Set([NIOSSLPrivateKey(customPrivateKey: firstKey), NIOSSLPrivateKey(customPrivateKey: secondKey), NIOSSLPrivateKey(customPrivateKey: thirdKey)]) + ) + } +} + + +extension SignatureAlgorithm { + var md: OpaquePointer { + switch self { + case .ecdsaSecp256R1Sha256: + return CNIOBoringSSL_EVP_sha256() + case .rsaPssRsaeSha256: + return CNIOBoringSSL_EVP_sha256() + case .rsaPkcs1Sha256: + return CNIOBoringSSL_EVP_sha256() + default: + preconditionFailure() + } + } + + var rsaPadding: CInt? { + switch self { + case .rsaPssRsaeSha256, .rsaPssRsaeSha384, .rsaPssRsaeSha512: + return CInt(RSA_PKCS1_PSS_PADDING) + case .rsaPkcs1Sha1, .rsaPkcs1Sha256, .rsaPkcs1Sha384, .rsaPkcs1Sha512: + return CInt(RSA_PKCS1_PADDING) + default: + return nil + } + } + + var saltLen: CInt? { + switch self { + case .rsaPssRsaeSha256, .rsaPssRsaeSha384, .rsaPssRsaeSha512: + // To BoringSSL, -1 means "salt length the size of the hash function". + // This is what TLS 1.3 requires. + return -1 + default: + return nil + } + } +} + +extension EmbeddedChannel { + fileprivate var handshakeSucceeded: Bool { + let completedHandler = try! self.pipeline.syncOperations.handler(type: HandshakeCompletedHandler.self) + return completedHandler.handshakeSucceeded + } +} diff --git a/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift b/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift index dc68558e..715640c2 100644 --- a/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift +++ b/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift @@ -457,7 +457,9 @@ class NIOSSLIntegrationTest: XCTestCase { let manager = BoringSSLPassphraseCallbackManager { closure in closure(passphrase.utf8) } let rc = withExtendedLifetime(manager) { manager -> CInt in let userData = Unmanaged.passUnretained(manager).toOpaque() - return CNIOBoringSSL_PEM_write_bio_PrivateKey(fileBio, key.ref, CNIOBoringSSL_EVP_aes_256_cbc(), nil, 0, globalBoringSSLPassphraseCallback, userData) + return key.withUnsafeMutableEVPPKEYPointer { ref in + return CNIOBoringSSL_PEM_write_bio_PrivateKey(fileBio, ref, CNIOBoringSSL_EVP_aes_256_cbc(), nil, 0, globalBoringSSLPassphraseCallback, userData) + } } CNIOBoringSSL_BIO_free(fileBio) precondition(rc == 1) diff --git a/Tests/NIOSSLTests/NIOSSLTestHelpers.swift b/Tests/NIOSSLTests/NIOSSLTestHelpers.swift index fbe273a1..9e7edffa 100644 --- a/Tests/NIOSSLTests/NIOSSLTestHelpers.swift +++ b/Tests/NIOSSLTests/NIOSSLTestHelpers.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -14,6 +14,8 @@ import Foundation @_implementationOnly import CNIOBoringSSL +import NIOCore +import NIOEmbedded @testable import NIOSSL let samplePemCert = """ @@ -589,6 +591,21 @@ func generateRSAPrivateKey() -> UnsafeMutablePointer { return pkey } +func generateECPrivateKey(curveNID: CInt = NID_X9_62_prime256v1) -> UnsafeMutablePointer { + let ctx = CNIOBoringSSL_EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nil)! + defer { + CNIOBoringSSL_EVP_PKEY_CTX_free(ctx) + } + + precondition(CNIOBoringSSL_EVP_PKEY_keygen_init(ctx) == 1) + precondition(CNIOBoringSSL_EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, curveNID) == 1) + + var pkey: UnsafeMutablePointer? = nil + precondition(CNIOBoringSSL_EVP_PKEY_keygen(ctx, &pkey) == 1) + + return pkey! +} + func addExtension(x509: OpaquePointer, nid: CInt, value: String) { var extensionContext = X509V3_CTX() @@ -600,8 +617,8 @@ func addExtension(x509: OpaquePointer, nid: CInt, value: String) { CNIOBoringSSL_X509_EXTENSION_free(ext) } -func generateSelfSignedCert() -> (NIOSSLCertificate, NIOSSLPrivateKey) { - let pkey = generateRSAPrivateKey() +func generateSelfSignedCert(keygenFunction: () -> UnsafeMutablePointer = generateRSAPrivateKey) -> (NIOSSLCertificate, NIOSSLPrivateKey) { + let pkey = keygenFunction() let x = CNIOBoringSSL_X509_new()! CNIOBoringSSL_X509_set_version(x, 2) @@ -648,3 +665,54 @@ func generateSelfSignedCert() -> (NIOSSLCertificate, NIOSSLPrivateKey) { return (NIOSSLCertificate.fromUnsafePointer(takingOwnership: x), NIOSSLPrivateKey.fromUnsafePointer(takingOwnership: pkey)) } + +final class BackToBackEmbeddedChannel { + private(set) var client: EmbeddedChannel + private(set) var server: EmbeddedChannel + private var loop: EmbeddedEventLoop + + + init() { + self.loop = EmbeddedEventLoop() + self.client = EmbeddedChannel(loop: self.loop) + self.server = EmbeddedChannel(loop: self.loop) + } + + func run() { + self.loop.run() + } + + func connectInMemory() throws { + let addr = try assertNoThrowWithValue(SocketAddress(unixDomainSocketPath: "/tmp/whatever2")) + let connectFuture = self.client.connect(to: addr) + self.server.pipeline.fireChannelActive() + try self.interactInMemory() + try connectFuture.wait() + } + + func interactInMemory() throws { + var workToDo = true + + while workToDo { + workToDo = false + + self.loop.run() + let clientDatum = try self.client.readOutbound(as: IOData.self) + let serverDatum = try self.server.readOutbound(as: IOData.self) + + // Reads may trigger errors. The write case is automatic. + try self.client.throwIfErrorCaught() + try self.server.throwIfErrorCaught() + + if let clientMsg = clientDatum { + try self.server.writeInbound(clientMsg) + workToDo = true + } + + if let serverMsg = serverDatum { + try self.client.writeInbound(serverMsg) + workToDo = true + } + } + } +}