Add TLS configuration object

This commit is contained in:
Cory Benfield committed 2017-09-29 14:25:46 +01:00
1 parent 7954a1bf18
commit 7dddd67608
15 files changed
+1215 -66

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(tvOS) || os(iOS)
import Darwin
#else
import Glibc
#endif
import OpenSSL
public class OpenSSLCertificate {
internal let ref: UnsafeMutablePointer<X509>
private init(withReference ref: UnsafeMutablePointer<X509>) {
self.ref = ref
}
/// Create an OpenSSLCertificate from a file at a given path in either PEM or
/// DER format.
public convenience init (file: String, format: OpenSSLSerializationFormats) throws {
let fileObject = file.withCString { filePtr in
return fopen(filePtr, "rb")
}
defer {
fclose(fileObject)
}
let x509: UnsafeMutablePointer<X509>?
switch format {
case .pem:
x509 = PEM_read_X509(fileObject, nil, nil, nil)
case .der:
x509 = d2i_X509_fp(fileObject, nil)
}
guard x509 != nil else {
throw NIOOpenSSLError.failedToLoadCertificate
}
self.init(withReference: x509!)
}
/// Create an OpenSSLCertificate from a buffer of bytes in either PEM or
/// DER format.
public convenience init (buffer: [Int8], format: OpenSSLSerializationFormats) throws {
let bio = buffer.withUnsafeBytes {
return BIO_new_mem_buf(UnsafeMutableRawPointer(mutating: $0.baseAddress!), Int32($0.count))!
}
defer {
BIO_free(bio)
}
let x509: UnsafeMutablePointer<X509>?
switch format {
case .pem:
x509 = PEM_read_bio_X509(bio, nil, nil, nil)
case .der:
x509 = d2i_X509_bio(bio, nil)
}
guard x509 != nil else {
throw NIOOpenSSLError.failedToLoadCertificate
}
self.init(withReference: x509!)
}
/// Create an OpenSSLCertificate wrapping a pointer into OpenSSL.
///
/// This is a function that should be avoided as much as possible because it plays poorly with
/// OpenSSL's reference-counted memory. This function does not increment the reference count for the X509
/// object here, nor does it duplicate it: it just takes ownership of the copy here. This object
/// **will** deallocate the underlying X509 object when deinited, and so if you need to keep that
/// X509 object alive you should call X509_dup before passing the pointer here.
///
/// In general, however, this function should be avoided in favour of one of the convenience
/// initializers, which ensure that the lifetime of the X509 object is better-managed.
static public func fromUnsafePointer(pointer: UnsafePointer<X509>) -> OpenSSLCertificate {
return OpenSSLCertificate(withReference: UnsafeMutablePointer(mutating: pointer))
}
deinit {
X509_free(ref)
}
}
extension OpenSSLCertificate: Equatable {
public static func ==(lhs: OpenSSLCertificate, rhs: OpenSSLCertificate) -> Bool {
return X509_cmp(lhs.ref, rhs.ref) == 0
}
}
+137 -49
View File
@@ -36,75 +36,173 @@ fileprivate var initialized: Bool = initializeOpenSSL()
}
#endif
private func verifyCallback(preverifyOk: Int32, ctx: UnsafeMutablePointer<X509_STORE_CTX>?) -> Int32 {
// This is a no-op verify callback for use with OpenSSL.
return preverifyOk
}
public final class SSLContext {
private let sslContext: UnsafeMutablePointer<SSL_CTX>
public init? () {
public init(configuration: TLSConfiguration) throws {
precondition(initialized)
guard let ctx = SSL_CTX_new(SSLv23_method()) else { return nil }
guard let ctx = SSL_CTX_new(SSLv23_method()) else { throw NIOOpenSSLError.unableToAllocateOpenSSLObject }
// TODO(cory): It doesn't seem like this initialization should happen here: where?
// TODO(cory): Probably there should be some kind of configuration struct that can be
// used to override our settings.
SSL_CTX_setAutoECDH(ctx)
assert(1 == SSL_CTX_set_default_verify_paths(ctx))
var opensslOptions = Int(SSL_OP_NO_COMPRESSION)
// Handle TLS versions
switch configuration.minimumTLSVersion {
case .tlsv13:
opensslOptions |= Int(SSL_OP_NO_TLSv1_2)
fallthrough
case .tlsv12:
opensslOptions |= Int(SSL_OP_NO_TLSv1_1)
fallthrough
case .tlsv11:
opensslOptions |= Int(SSL_OP_NO_TLSv1)
fallthrough
case .tlsv1:
opensslOptions |= Int(SSL_OP_NO_SSLv3)
fallthrough
case .sslv3:
opensslOptions |= Int(SSL_OP_NO_SSLv2)
fallthrough
case .sslv2:
break
}
switch configuration.maximumTLSVersion {
case .some(.sslv2):
opensslOptions |= Int(SSL_OP_NO_SSLv3)
fallthrough
case .some(.sslv3):
opensslOptions |= Int(SSL_OP_NO_TLSv1)
fallthrough
case .some(.tlsv1):
opensslOptions |= Int(SSL_OP_NO_TLSv1_1)
fallthrough
case .some(.tlsv11):
opensslOptions |= Int(SSL_OP_NO_TLSv1_2)
case .some(.tlsv12), .some(.tlsv13), .none:
break
}
// It's not really very clear here, but this is the actual way to spell SSL_CTX_set_options in Swift code.
// Sadly, SSL_CTX_set_options is a macro, which means we cannot use it directly, and our modulemap doesn't
// reveal it in a helpful way, so we write it like this instead.
SSL_CTX_ctrl(ctx, SSL_CTRL_OPTIONS, Int(SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION), nil)
SSL_CTX_ctrl(ctx, SSL_CTRL_OPTIONS, opensslOptions, nil)
// Cipher suites. We just pass this straight to OpenSSL.
configuration.cipherSuites.withCString {
precondition(1 == SSL_CTX_set_cipher_list(ctx, $0))
}
// If validation is turned on, set the trust roots and turn on cert validation.
if configuration.certificateVerification {
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verifyCallback)
switch configuration.trustRoots {
case .some(.default), .none:
precondition(1 == SSL_CTX_set_default_verify_paths(ctx))
case .some(.file(let f)):
try SSLContext.loadVerifyLocations(f, context: ctx)
case .some(.certificates(let certs)):
try certs.forEach { try SSLContext.addRootCertificate($0, context: ctx) }
}
}
// If we were given a certificate chain to use, load it and its associated private key.
var leaf = true
try configuration.certificateChain.forEach {
switch $0 {
case .file(let p):
SSLContext.useCertificateChainFile(p, context:ctx)
leaf = false
case .certificate(let cert):
if leaf {
try SSLContext.setLeafCertificate(cert, context: ctx)
leaf = false
} else {
try SSLContext.addAdditionalChainCertificate(cert, context: ctx)
}
}
}
if let pkey = configuration.privateKey {
switch pkey {
case .file(let p):
SSLContext.usePrivateKeyFile(p, context: ctx)
case .privateKey(let key):
try SSLContext.setPrivateKey(key, context: ctx)
}
}
sslContext = ctx
}
public func useCertificateChainFile(atPath: URL) {
internal func createConnection() -> SSLConnection? {
guard let ssl = SSL_new(sslContext) else {
return nil
}
return SSLConnection(ssl, parentContext:self)
}
deinit {
SSL_CTX_free(sslContext)
}
}
extension SSLContext {
private static func useCertificateChainFile(_ path: String, context: UnsafeMutablePointer<SSL_CTX>) {
// TODO(cory): This shouldn't be an assert but should instead be actual error handling.
// assert(atPath.isFileURL)
let result = atPath.withUnsafeFileSystemRepresentation { (pointer) -> Int32 in
return SSL_CTX_use_certificate_chain_file(sslContext, pointer)
// assert(path.isFileURL)
let result = path.withCString { (pointer) -> Int32 in
return SSL_CTX_use_certificate_chain_file(context, pointer)
}
// TODO(cory): again, some error handling would be good.
assert(result == 1)
precondition(result == 1)
}
// TODO(cory): There should really be a wrapper object here with some useful methods, not least because
// otherwise it's very easy to leak these cert objects, but for now this will do.
public func setLeafCertificate(_ cert: UnsafeMutablePointer<X509>) throws {
let rc = SSL_CTX_use_certificate(sslContext, cert)
private static func setLeafCertificate(_ cert: OpenSSLCertificate, context: UnsafeMutablePointer<SSL_CTX>) throws {
let rc = SSL_CTX_use_certificate(context, cert.ref)
guard rc == 1 else {
throw NIOOpenSSLError.failedToLoadCertificate
}
}
public func addAdditionalChainCertificate(_ cert: UnsafeMutablePointer<X509>) throws {
// TODO(cory): When we add a wrapper here, we probably need to do an X509_dup here
// to avoid leaking the additional chain cert: as far as I can tell SSL_CTX_ctrl doesn't
// retain the extra cert objects.
guard 1 == SSL_CTX_ctrl(sslContext, SSL_CTRL_EXTRA_CHAIN_CERT, 0, cert) else {
private static func addAdditionalChainCertificate(_ cert: OpenSSLCertificate, context: UnsafeMutablePointer<SSL_CTX>) throws {
// This dup is necessary because the SSL_CTX_ctrl doesn't copy the X509 object itself.
guard 1 == SSL_CTX_ctrl(context, SSL_CTRL_EXTRA_CHAIN_CERT, 0, X509_dup(cert.ref)) else {
throw NIOOpenSSLError.failedToLoadCertificate
}
}
public func setPrivateKey(_ key: UnsafeMutablePointer<EVP_PKEY>) throws {
guard 1 == SSL_CTX_use_PrivateKey(sslContext, key) else {
private static func setPrivateKey(_ key: OpenSSLPrivateKey, context: UnsafeMutablePointer<SSL_CTX>) throws {
guard 1 == SSL_CTX_use_PrivateKey(context, key.ref) else {
throw NIOOpenSSLError.failedToLoadPrivateKey
}
}
public func addRootCertificate(_ cert: UnsafeMutablePointer<X509>) throws {
let store = SSL_CTX_get_cert_store(sslContext)!
guard 0 != X509_STORE_add_cert(store, cert) else {
private static func addRootCertificate(_ cert: OpenSSLCertificate, context: UnsafeMutablePointer<SSL_CTX>) throws {
let store = SSL_CTX_get_cert_store(context)!
guard 0 != X509_STORE_add_cert(store, cert.ref) else {
throw NIOOpenSSLError.failedToLoadCertificate
}
}
public func usePrivateKeyFile(atPath: URL) {
private static func usePrivateKeyFile(_ path: String, context: UnsafeMutablePointer<SSL_CTX>) {
// TODO(cory): This shouldn't be an assert but should instead be actual error handling.
// assert(atPath.isFileURL)
let path = URL(string: path)!
let fileType: Int32
switch atPath.pathExtension.lowercased() {
switch path.pathExtension.lowercased() {
case "pem":
fileType = SSL_FILETYPE_PEM
case "der", "key":
@@ -114,25 +212,25 @@ public final class SSLContext {
fatalError("Unknown private key file type.")
}
let result = atPath.withUnsafeFileSystemRepresentation { (pointer) -> Int32 in
return SSL_CTX_use_PrivateKey_file(sslContext, pointer, fileType)
let result = path.withUnsafeFileSystemRepresentation { (pointer) -> Int32 in
return SSL_CTX_use_PrivateKey_file(context, pointer, fileType)
}
// TODO(cory): again, some error handling would be good.
assert(result == 1)
precondition(result == 1)
}
public func loadVerifyLocations(atPath: String) throws {
private static func loadVerifyLocations(_ path: String, context: UnsafeMutablePointer<SSL_CTX>) throws {
var isDirectory: ObjCBool = false
let exists = FileManager().fileExists(atPath: atPath, isDirectory: &isDirectory)
let exists = FileManager().fileExists(atPath: path, isDirectory: &isDirectory)
guard exists else {
throw NIOOpenSSLError.noSuchFilesystemObject
}
let result = atPath.withCString { (pointer) -> Int32 in
let result = path.withCString { (pointer) -> Int32 in
let file = !(isDirectory.boolValue) ? pointer : nil
let directory = isDirectory.boolValue ? pointer: nil
return SSL_CTX_load_verify_locations(sslContext, file, directory)
return SSL_CTX_load_verify_locations(context, file, directory)
}
if result == 0 {
@@ -140,15 +238,5 @@ public final class SSLContext {
throw OpenSSLError.unknownError(errorStack)
}
}
internal func createConnection() -> SSLConnection? {
guard let ssl = SSL_new(sslContext) else {
return nil
}
return SSLConnection(ssl, parentContext:self)
}
deinit {
SSL_CTX_free(sslContext)
}
}
+5 -1
View File
@@ -19,7 +19,7 @@ import OpenSSL
import Glibc
#endif
public struct OpenSSLInternalError: Equatable {
public struct OpenSSLInternalError: Equatable, CustomStringConvertible {
let errorCode: u_long
var errorMessage: String? {
@@ -29,6 +29,10 @@ public struct OpenSSLInternalError: Equatable {
return nil
}
public var description: String {
return"Error: \(errorCode) \(errorMessage ?? "")"
}
init(errorCode: u_long) {
self.errorCode = errorCode
}
+102
View File
@@ -0,0 +1,102 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(tvOS) || os(iOS)
import Darwin
#else
import Glibc
#endif
import OpenSSL
public class OpenSSLPrivateKey {
internal let ref: UnsafeMutablePointer<EVP_PKEY>
private init(withReference ref: UnsafeMutablePointer<EVP_PKEY>) {
self.ref = ref
}
/// Create an OpenSSLPrivateKey from a file at a given path in either PEM or
/// DER format.
public convenience init (file: String, format: OpenSSLSerializationFormats) throws {
let fileObject = file.withCString { filePtr in
return fopen(filePtr, "rb")
}
defer {
fclose(fileObject)
}
let key: UnsafeMutablePointer<EVP_PKEY>?
switch format {
case .pem:
key = PEM_read_PrivateKey(fileObject, nil, nil, nil)
case .der:
key = d2i_PrivateKey_fp(fileObject, nil)
}
guard key != nil else {
throw NIOOpenSSLError.failedToLoadPrivateKey
}
self.init(withReference: key!)
}
/// Create an OpenSSLPrivateKey from a buffer of bytes in either PEM or
/// DER format.
public convenience init (buffer: [Int8], format: OpenSSLSerializationFormats) throws {
let bio = buffer.withUnsafeBytes {
return BIO_new_mem_buf(UnsafeMutableRawPointer(mutating: $0.baseAddress!), Int32($0.count))!
}
defer {
BIO_free(bio)
}
let key: UnsafeMutablePointer<EVP_PKEY>?
switch format {
case .pem:
key = PEM_read_bio_PrivateKey(bio, nil, nil, nil)
case .der:
key = d2i_PrivateKey_bio(bio, nil)
}
guard key != nil else {
throw NIOOpenSSLError.failedToLoadPrivateKey
}
self.init(withReference: key!)
}
/// Create an OpenSSLPrivateKey wrapping a pointer into OpenSSL.
///
/// This is a function that should be avoided as much as possible because it plays poorly with
/// OpenSSL's reference-counted memory. This function does not increment the reference count for the EVP_PKEY
/// object here, nor does it duplicate it: it just takes ownership of the copy here. This object
/// **will** deallocate the underlying EVP_PKEY object when deinited, and so if you need to keep that
/// EVP_PKEY object alive you should call X509_dup before passing the pointer here.
///
/// In general, however, this function should be avoided in favour of one of the convenience
/// initializers, which ensure that the lifetime of the X509 object is better-managed.
static public func fromUnsafePointer(pointer: UnsafePointer<EVP_PKEY>) -> OpenSSLPrivateKey {
return OpenSSLPrivateKey(withReference: UnsafeMutablePointer(mutating: pointer))
}
deinit {
EVP_PKEY_free(ref)
}
}
extension OpenSSLPrivateKey: Equatable {
public static func ==(lhs: OpenSSLPrivateKey, rhs: OpenSSLPrivateKey) -> Bool {
return EVP_PKEY_cmp(lhs.ref, rhs.ref) != 0
}
}
+161
View File
@@ -0,0 +1,161 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import OpenSSL
public enum TLSVersion {
case sslv2
case sslv3
case tlsv1
case tlsv11
case tlsv12
case tlsv13
}
public enum OpenSSLCertificateSource {
case file(String)
case certificate(OpenSSLCertificate)
}
public enum OpenSSLPrivateKeySource {
case file(String)
case privateKey(OpenSSLPrivateKey)
}
public enum OpenSSLTrustRoots {
case file(String)
case certificates([OpenSSLCertificate])
case `default`
}
public enum OpenSSLSerializationFormats {
case pem
case der
}
/// A secure default configuration of cipher suites.
///
/// The goal of this cipher suite string is:
/// - Prefer TLS 1.3 cipher suites.
/// - Prefer cipher suites that offer Perfect Forward Secrecy (DHE/ECDHE)
/// - Prefer ECDH(E) to DH(E) for performance.
/// - Prefer any AEAD cipher suite over non-AEAD suites for better performance and security
/// - Prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common
/// - Disable NULL authentication and encryption and any appearance of MD5
public let defaultCipherSuites = [
"TLS13-AES-256-GCM-SHA384",
"TLS13-CHACHA20-POLY1305-SHA256",
"TLS13-AES-128-GCM-SHA256",
"ECDH+AESGCM",
"ECDH+CHACHA20",
"DH+AESGCM",
"DH+CHACHA20",
"ECDH+AES256",
"DH+AES256",
"ECDH+AES128",
"DH+AES",
"RSA+AESGCM",
"RSA+AES",
"!aNULL",
"!eNULL",
"!MD5",
].joined(separator: ":")
/// Manages configuration of OpenSSL for SwiftNIO programs.
///
/// OpenSSL has a number of configuration options that are worth setting. This structure allows
/// setting those options in a more expressive manner than OpenSSL itself allows.
public struct TLSConfiguration {
/// A default TLS configuration for client use.
public static let clientDefault = TLSConfiguration.forClient()
/// The minimum TLS version to allow in negotiation. Defaults to tlsv1.
public let minimumTLSVersion: TLSVersion
/// The maximum TLS version to allow in negotiation. If nil, there is no upper limit. Defaults to nil.
public let maximumTLSVersion: TLSVersion?
/// The cipher suites supported by this handler. This uses the OpenSSL cipher string format.
public let cipherSuites: String
/// Whether to verify remote certificates.
public let certificateVerification: Bool
/// The trust roots to use to validate certificates. This only needs to be provided if you intend to validate
/// certificates.
public let trustRoots: OpenSSLTrustRoots?
/// The certificates to offer during negotiation. If not present, no certificates will be offered.
public let certificateChain: [OpenSSLCertificateSource]
/// The private key associated with the leaf certificate.
public let privateKey: OpenSSLPrivateKeySource?
private init(cipherSuites: String,
minimumTLSVersion: TLSVersion,
maximumTLSVersion: TLSVersion?,
certificateVerification: Bool,
trustRoots: OpenSSLTrustRoots,
certificateChain: [OpenSSLCertificateSource],
privateKey: OpenSSLPrivateKeySource?) {
self.cipherSuites = cipherSuites
self.minimumTLSVersion = minimumTLSVersion
self.maximumTLSVersion = maximumTLSVersion
self.certificateVerification = certificateVerification
self.trustRoots = trustRoots
self.certificateChain = certificateChain
self.privateKey = privateKey
}
/// Create a TLS configuration for use with server-side contexts.
///
/// This provides sensible defaults while requiring that you provide any data that is necessary
/// for server-side function. For client use, try `forClient` instead.
public static func forServer(certificateChain: [OpenSSLCertificateSource],
privateKey: OpenSSLPrivateKeySource,
cipherSuites: String = defaultCipherSuites,
minimumTLSVersion: TLSVersion = .tlsv1,
maximumTLSVersion: TLSVersion? = nil,
certificateVerification: Bool = false,
trustRoots: OpenSSLTrustRoots = .default) -> TLSConfiguration {
return TLSConfiguration(cipherSuites: cipherSuites,
minimumTLSVersion: minimumTLSVersion,
maximumTLSVersion: maximumTLSVersion,
certificateVerification: certificateVerification,
trustRoots: trustRoots,
certificateChain: certificateChain,
privateKey: privateKey)
}
/// Creates a TLS configuration for use with client-side contexts.
///
/// This provides sensible defaults, and can be used without customisation. For server-side
/// contexts, you should use `forServer` instead.
public static func forClient(cipherSuites: String = defaultCipherSuites,
minimumTLSVersion: TLSVersion = .tlsv1,
maximumTLSVersion: TLSVersion? = nil,
certificateVerification: Bool = true,
trustRoots: OpenSSLTrustRoots = .default,
certificateChain: [OpenSSLCertificateSource] = [],
privateKey: OpenSSLPrivateKeySource? = nil) -> TLSConfiguration {
return TLSConfiguration(cipherSuites: cipherSuites,
minimumTLSVersion: minimumTLSVersion,
maximumTLSVersion: maximumTLSVersion,
certificateVerification: certificateVerification,
trustRoots: trustRoots,
certificateChain: certificateChain,
privateKey: privateKey)
}
}
+1 -3
View File
@@ -29,9 +29,7 @@ private final class EchoHandler: ChannelInboundHandler {
}
}
let sslContext = SSLContext()!
sslContext.useCertificateChainFile(atPath: URL.init(string: "cert.pem")!)
sslContext.usePrivateKeyFile(atPath: URL.init(string: "key.pem")!)
let sslContext = try! SSLContext(configuration: TLSConfiguration.forServer(certificateChain: [.file("cert.pem")], privateKey: .file("key.pem")))
let group = try MultiThreadedEventLoopGroup(numThreads: 1)
+3
View File
@@ -45,7 +45,10 @@ import XCTest
testCase(MarkedCircularBufferTests.allTests),
testCase(MessageToByteEncoderTest.allTests),
testCase(OpenSSLIntegrationTest.allTests),
testCase(SSLCertificateTest.allTests),
testCase(SSLPrivateKeyTest.allTests),
testCase(SocketAddressTest.allTests),
testCase(TLSConfigurationTest.allTests),
testCase(TypeAssistedChannelHandlerTest.allTests),
])
#endif
@@ -150,7 +150,7 @@ public final class EventRecorderHandler<UserEventType>: ChannelInboundHandler wh
}
}
private func serverTLSChannel(withContext: NIOOpenSSL.SSLContext, andHandlers: [ChannelHandler], onGroup: EventLoopGroup) throws -> Channel {
internal func serverTLSChannel(withContext: NIOOpenSSL.SSLContext, andHandlers: [ChannelHandler], onGroup: EventLoopGroup) throws -> Channel {
return try ServerBootstrap(group: onGroup)
.option(option: ChannelOptions.Socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.handler(childHandler: ChannelInitializer(initChannel: { channel in
@@ -165,7 +165,7 @@ private func serverTLSChannel(withContext: NIOOpenSSL.SSLContext, andHandlers: [
})).bind(to: "127.0.0.1", on: 0).wait()
}
private func clientTLSChannel(withContext: NIOOpenSSL.SSLContext,
internal func clientTLSChannel(withContext: NIOOpenSSL.SSLContext,
preHandlers: [ChannelHandler],
postHandlers: [ChannelHandler],
onGroup: EventLoopGroup,
@@ -188,8 +188,8 @@ private func clientTLSChannel(withContext: NIOOpenSSL.SSLContext,
}
class OpenSSLIntegrationTest: XCTestCase {
static var cert: UnsafeMutablePointer<X509>!
static var key: UnsafeMutablePointer<EVP_PKEY>!
static var cert: OpenSSLCertificate!
static var key: OpenSSLPrivateKey!
override class func setUp() {
super.setUp()
@@ -199,10 +199,10 @@ class OpenSSLIntegrationTest: XCTestCase {
}
private func configuredSSLContext() throws -> NIOOpenSSL.SSLContext {
let ctx = SSLContext()!
try ctx.setLeafCertificate(OpenSSLIntegrationTest.cert)
try ctx.setPrivateKey(OpenSSLIntegrationTest.key)
try ctx.addRootCertificate(OpenSSLIntegrationTest.cert)
let config = TLSConfiguration.forServer(certificateChain: [.certificate(OpenSSLIntegrationTest.cert)],
privateKey: .privateKey(OpenSSLIntegrationTest.key),
trustRoots: .certificates([OpenSSLIntegrationTest.cert]))
let ctx = try SSLContext(configuration: config)
return ctx
}
+120 -5
View File
@@ -12,12 +12,127 @@
//
//===----------------------------------------------------------------------===//
import Foundation
import OpenSSL
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
import NIOOpenSSL
let samplePemCert = """
-----BEGIN CERTIFICATE-----
MIIGGzCCBAOgAwIBAgIJAJ/X0Fo0ynmEMA0GCSqGSIb3DQEBCwUAMIGjMQswCQYD
VQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5z
b2t5bzEuMCwGA1UECgwlU2FuIEZyYW5zb2t5byBJbnN0aXR1dGUgb2YgVGVjaG5v
bG9neTEVMBMGA1UECwwMUm9ib3RpY3MgTGFiMSAwHgYDVQQDDBdyb2JvdHMuc2Fu
ZnJhbnNva3lvLmVkdTAeFw0xNzEwMTYyMTAxMDJaFw00NzEwMDkyMT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0qqMc5gpnRdKqpmNZZ8xbOYdvUGfPg1
XwsbAoIBAGdH7iRU/mp8SP48/oC1/HwqmEcuIDo40JE2t6hflGkav3npPLMp2XXi
xxK+egokeXWW4e0nHNBZXM3e+/JixY3FL+E65QDfWGjoIPkgcN3/clJsO3vY47Ww
rAv0GtS3xKEwA1OGy7rfmIZE72xW84+HwmXQPltbAVjOm52jj1sO6eVMIFY5TlGE
uYf+Gkez0+lXchItaEW+2v5h8S7XpRAmkcgrjDHnDcqNy19vXKOm8pvWJDBppZxq
A05qa1J7byekprhP+H9gnbBJsimsv/3zL19oOZ/ROBx98S/+ULZbMh/H1BWUqFI7
36Da/L/1cJBAo6JkEPLr9VCjJwgqCEECggEBAI6+35Lf4jDwRPvZV7kE+FQuFp1G
/tKxIJtPOZU3sbOVlsFsOoyEfV6+HbpeWxlWnrOnKRFOLoC3s5MVTjPglu1rC0ZX
4b0wMetvun5S1MGadB808rvu5EsEB1vznz1vOXV8oDdkdgBiiUcKewSeCrG1IrXy
B9ux859S3JjELzeuNdz+xHqu2AqR22gtqN72tJUEQ95qLGZ8vo+ytY9MDVDqoSWJ
9pqHXFUVLmwHTM0/pciXN4Kx1IL9FZ3fjXgME0vdYpWYQkcvSKLsswXN+LnYcpoQ
h33H/Kz4yji7jPN6Uk9wMyG7XGqpjYAuKCd6V3HEHUiGJZzho/VBgb3TVnw=
-----END RSA PRIVATE KEY-----
"""
let sampleDerCert = pemToDer(samplePemCert)
let sampleDerKey = pemToDer(samplePemKey)
func pemToDer(_ pem: String) -> Data {
var lines = [String]()
// This is very inefficient, but it doesn't really matter because this
// code is run very infrequently and only in testing. Blame the inefficiency
// on Linux Foundation, which currently lacks String.enumerateLines.
let originalLines = pem.split(separator: "\n")
for line in originalLines {
let line = String(line)
if !line.hasPrefix("-----") {
lines.append(line)
}
}
let encodedData = lines.joined(separator: "")
return Data(base64Encoded: encodedData)!
}
// This function generates a random number suitable for use in an X509
// serial field. This needs to be a positive number less than 2^159
@@ -80,7 +195,7 @@ func addExtension(x509: UnsafeMutablePointer<X509>, nid: Int32, value: String) {
X509_EXTENSION_free(ext)
}
func generateSelfSignedCert() -> (UnsafeMutablePointer<X509>, UnsafeMutablePointer<EVP_PKEY>) {
func generateSelfSignedCert() -> (OpenSSLCertificate, OpenSSLPrivateKey) {
let pkey = generateRSAPrivateKey()
let x = X509_new()!
X509_set_version(x, 3)
@@ -91,14 +206,14 @@ func generateSelfSignedCert() -> (UnsafeMutablePointer<X509>, UnsafeMutablePoint
X509_set_serialNumber(x, &serial)
let notBefore = ASN1_TIME_new()!
var now = time_t()
ASN1_TIME_set(notBefore, time(&now))
var now = time(nil)
ASN1_TIME_set(notBefore, now)
X509_set_notBefore(x, notBefore)
ASN1_TIME_free(notBefore)
now += 60 * 60 // Give ourselves an hour
let notAfter = ASN1_TIME_new()!
ASN1_TIME_set(notAfter, time(&now))
ASN1_TIME_set(notAfter, now)
X509_set_notAfter(x, notAfter)
ASN1_TIME_free(notAfter)
@@ -125,5 +240,5 @@ func generateSelfSignedCert() -> (UnsafeMutablePointer<X509>, UnsafeMutablePoint
X509_sign(x, pkey, EVP_sha256())
return (x, pkey)
return (OpenSSLCertificate.fromUnsafePointer(pointer: x), OpenSSLPrivateKey.fromUnsafePointer(pointer: pkey))
}
@@ -0,0 +1,41 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// SSLCertificateTest+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 SSLCertificateTest {
static var allTests : [(String, (SSLCertificateTest) -> () throws -> Void)] {
return [
("testLoadingPemCertFromFile", testLoadingPemCertFromFile),
("testLoadingDerCertFromFile", testLoadingDerCertFromFile),
("testDerAndPemAreIdentical", testDerAndPemAreIdentical),
("testLoadingPemCertFromMemory", testLoadingPemCertFromMemory),
("testLoadingDerCertFromMemory", testLoadingDerCertFromMemory),
("testLoadingGibberishFromMemoryAsPemFails", testLoadingGibberishFromMemoryAsPemFails),
("testLoadingGibberishFromMemoryAsDerFails", testLoadingGibberishFromMemoryAsDerFails),
("testLoadingGibberishFromFileAsPemFails", testLoadingGibberishFromFileAsPemFails),
("testLoadingGibberishFromFileAsDerFails", testLoadingGibberishFromFileAsDerFails),
]
}
}
@@ -0,0 +1,163 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
@testable import NIO
@testable import NIOOpenSSL
private func makeTemporaryFile() -> String {
let template = "/tmp/niotestXXXXXXX"
var templateBytes = Array(template.utf8)
templateBytes.append(0)
_ = templateBytes.withUnsafeMutableBufferPointer { ptr in
ptr.baseAddress!.withMemoryRebound(to: Int8.self, capacity: templateBytes.count) { (ptr: UnsafeMutablePointer<Int8>) in
return mktemp(ptr)
}
}
templateBytes.removeLast()
return String(decoding: templateBytes, as: UTF8.self)
}
internal func dumpToFile(data: Data) throws -> String {
let filename = makeTemporaryFile()
try data.write(to: URL(fileURLWithPath: filename))
return filename
}
internal func dumpToFile(text: String) throws -> String {
return try dumpToFile(data: text.data(using: .utf8)!)
}
internal extension Data {
func asArray() -> [Int8] {
return self.withUnsafeBytes { (dataPtr: UnsafePointer<UInt8>) -> [Int8] in
return dataPtr.withMemoryRebound(to: Int8.self, capacity: self.count) { reboundPtr in
let tempBuffer = UnsafeBufferPointer(start: reboundPtr, count: self.count)
return [Int8](tempBuffer)
}
}
}
}
class SSLCertificateTest: XCTestCase {
static var pemCertFilePath: String! = nil
static var derCertFilePath: String! = nil
static var dynamicallyGeneratedCert: OpenSSLCertificate! = nil
override class func setUp() {
SSLCertificateTest.pemCertFilePath = try! dumpToFile(text: samplePemCert)
SSLCertificateTest.derCertFilePath = try! dumpToFile(data: sampleDerCert)
let (cert, _) = generateSelfSignedCert()
SSLCertificateTest.dynamicallyGeneratedCert = cert
}
override class func tearDown() {
_ = SSLCertificateTest.pemCertFilePath.withCString {
unlink($0)
}
_ = SSLCertificateTest.derCertFilePath.withCString {
unlink($0)
}
}
func testLoadingPemCertFromFile() throws {
let cert1 = try OpenSSLCertificate(file: SSLCertificateTest.pemCertFilePath, format: .pem)
let cert2 = try OpenSSLCertificate(file: SSLCertificateTest.pemCertFilePath, format: .pem)
XCTAssertEqual(cert1, cert2)
XCTAssertNotEqual(cert1, SSLCertificateTest.dynamicallyGeneratedCert)
}
func testLoadingDerCertFromFile() throws {
let cert1 = try OpenSSLCertificate(file: SSLCertificateTest.derCertFilePath, format: .der)
let cert2 = try OpenSSLCertificate(file: SSLCertificateTest.derCertFilePath, format: .der)
XCTAssertEqual(cert1, cert2)
XCTAssertNotEqual(cert1, SSLCertificateTest.dynamicallyGeneratedCert)
}
func testDerAndPemAreIdentical() throws {
let cert1 = try OpenSSLCertificate(file: SSLCertificateTest.pemCertFilePath, format: .pem)
let cert2 = try OpenSSLCertificate(file: SSLCertificateTest.derCertFilePath, format: .der)
XCTAssertEqual(cert1, cert2)
}
func testLoadingPemCertFromMemory() throws {
let cert1 = try OpenSSLCertificate(buffer: [Int8](samplePemCert.utf8CString), format: .pem)
let cert2 = try OpenSSLCertificate(buffer: [Int8](samplePemCert.utf8CString), format: .pem)
XCTAssertEqual(cert1, cert2)
}
func testLoadingDerCertFromMemory() throws {
let certBuffer = sampleDerCert.asArray()
let cert1 = try OpenSSLCertificate(buffer: certBuffer, format: .der)
let cert2 = try OpenSSLCertificate(buffer: certBuffer, format: .der)
XCTAssertEqual(cert1, cert2)
}
func testLoadingGibberishFromMemoryAsPemFails() throws {
let keyBuffer: [Int8] = [1, 2, 3]
do {
_ = try OpenSSLCertificate(buffer: keyBuffer, format: .pem)
XCTFail("Gibberish successfully loaded")
} catch NIOOpenSSLError.failedToLoadCertificate {
// Do nothing.
}
}
func testLoadingGibberishFromMemoryAsDerFails() throws {
let keyBuffer: [Int8] = [1, 2, 3]
do {
_ = try OpenSSLCertificate(buffer: keyBuffer, format: .der)
XCTFail("Gibberish successfully loaded")
} catch NIOOpenSSLError.failedToLoadCertificate {
// Do nothing.
}
}
func testLoadingGibberishFromFileAsPemFails() throws {
let tempFile = try dumpToFile(text: "hello")
defer {
_ = tempFile.withCString { unlink($0) }
}
do {
_ = try OpenSSLCertificate(file: tempFile, format: .pem)
XCTFail("Gibberish successfully loaded")
} catch NIOOpenSSLError.failedToLoadCertificate {
// Do nothing.
}
}
func testLoadingGibberishFromFileAsDerFails() throws {
let tempFile = try dumpToFile(text: "hello")
defer {
_ = tempFile.withCString { unlink($0) }
}
do {
_ = try OpenSSLCertificate(file: tempFile, format: .der)
XCTFail("Gibberish successfully loaded")
} catch NIOOpenSSLError.failedToLoadCertificate {
// Do nothing.
}
}
}
@@ -0,0 +1,41 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// SSLPrivateKeyTests+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 SSLPrivateKeyTest {
static var allTests : [(String, (SSLPrivateKeyTest) -> () throws -> Void)] {
return [
("testLoadingPemKeyFromFile", testLoadingPemKeyFromFile),
("testLoadingDerKeyFromFile", testLoadingDerKeyFromFile),
("testDerAndPemAreIdentical", testDerAndPemAreIdentical),
("testLoadingPemKeyFromMemory", testLoadingPemKeyFromMemory),
("testLoadingDerKeyFromMemory", testLoadingDerKeyFromMemory),
("testLoadingGibberishFromMemoryAsPemFails", testLoadingGibberishFromMemoryAsPemFails),
("testLoadingGibberishFromMemoryAsDerFails", testLoadingGibberishFromMemoryAsDerFails),
("testLoadingGibberishFromFileAsPemFails", testLoadingGibberishFromFileAsPemFails),
("testLoadingGibberishFromFileAsDerFails", testLoadingGibberishFromFileAsDerFails),
]
}
}
@@ -0,0 +1,129 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
@testable import NIO
@testable import NIOOpenSSL
class SSLPrivateKeyTest: XCTestCase {
static var pemKeyFilePath: String! = nil
static var derKeyFilePath: String! = nil
static var dynamicallyGeneratedKey: OpenSSLPrivateKey! = nil
override class func setUp() {
SSLPrivateKeyTest.pemKeyFilePath = try! dumpToFile(text: samplePemKey)
SSLPrivateKeyTest.derKeyFilePath = try! dumpToFile(data: sampleDerKey)
let (_, key) = generateSelfSignedCert()
SSLPrivateKeyTest.dynamicallyGeneratedKey = key
}
override class func tearDown() {
_ = SSLPrivateKeyTest.pemKeyFilePath.withCString {
unlink($0)
}
_ = SSLPrivateKeyTest.derKeyFilePath.withCString {
unlink($0)
}
}
func testLoadingPemKeyFromFile() throws {
let key1 = try OpenSSLPrivateKey(file: SSLPrivateKeyTest.pemKeyFilePath, format: .pem)
let key2 = try OpenSSLPrivateKey(file: SSLPrivateKeyTest.pemKeyFilePath, format: .pem)
XCTAssertEqual(key1, key2)
XCTAssertNotEqual(key1, SSLPrivateKeyTest.dynamicallyGeneratedKey)
}
func testLoadingDerKeyFromFile() throws {
let key1 = try OpenSSLPrivateKey(file: SSLPrivateKeyTest.derKeyFilePath, format: .der)
let key2 = try OpenSSLPrivateKey(file: SSLPrivateKeyTest.derKeyFilePath, format: .der)
XCTAssertEqual(key1, key2)
XCTAssertNotEqual(key1, SSLPrivateKeyTest.dynamicallyGeneratedKey)
}
func testDerAndPemAreIdentical() throws {
let key1 = try OpenSSLPrivateKey(file: SSLPrivateKeyTest.pemKeyFilePath, format: .pem)
let key2 = try OpenSSLPrivateKey(file: SSLPrivateKeyTest.derKeyFilePath, format: .der)
XCTAssertEqual(key1, key2)
}
func testLoadingPemKeyFromMemory() throws {
let key1 = try OpenSSLPrivateKey(buffer: [Int8](samplePemKey.utf8CString), format: .pem)
let key2 = try OpenSSLPrivateKey(buffer: [Int8](samplePemKey.utf8CString), format: .pem)
XCTAssertEqual(key1, key2)
}
func testLoadingDerKeyFromMemory() throws {
let keyBuffer = sampleDerKey.asArray()
let key1 = try OpenSSLPrivateKey(buffer: keyBuffer, format: .der)
let key2 = try OpenSSLPrivateKey(buffer: keyBuffer, format: .der)
XCTAssertEqual(key1, key2)
}
func testLoadingGibberishFromMemoryAsPemFails() throws {
let keyBuffer: [Int8] = [1, 2, 3]
do {
_ = try OpenSSLPrivateKey(buffer: keyBuffer, format: .pem)
XCTFail("Gibberish successfully loaded")
} catch NIOOpenSSLError.failedToLoadPrivateKey {
// Do nothing.
}
}
func testLoadingGibberishFromMemoryAsDerFails() throws {
let keyBuffer: [Int8] = [1, 2, 3]
do {
_ = try OpenSSLPrivateKey(buffer: keyBuffer, format: .der)
XCTFail("Gibberish successfully loaded")
} catch NIOOpenSSLError.failedToLoadPrivateKey {
// Do nothing.
}
}
func testLoadingGibberishFromFileAsPemFails() throws {
let tempFile = try dumpToFile(text: "hello")
defer {
_ = tempFile.withCString { unlink($0) }
}
do {
_ = try OpenSSLPrivateKey(file: tempFile, format: .pem)
XCTFail("Gibberish successfully loaded")
} catch NIOOpenSSLError.failedToLoadPrivateKey {
// Do nothing.
}
}
func testLoadingGibberishFromFileAsDerFails() throws {
let tempFile = try dumpToFile(text: "hello")
defer {
_ = tempFile.withCString { unlink($0) }
}
do {
_ = try OpenSSLPrivateKey(file: tempFile, format: .der)
XCTFail("Gibberish successfully loaded")
} catch NIOOpenSSLError.failedToLoadPrivateKey {
// Do nothing.
}
}
}
@@ -0,0 +1,37 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// TLSConfigurationTest+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 TLSConfigurationTest {
static var allTests : [(String, (TLSConfigurationTest) -> () throws -> Void)] {
return [
("testNonOverlappingTLSVersions", testNonOverlappingTLSVersions),
("testNonOverlappingCipherSuites", testNonOverlappingCipherSuites),
("testCannotVerifySelfSigned", testCannotVerifySelfSigned),
("testServerCannotValidateClient", testServerCannotValidateClient),
("testMutualValidation", testMutualValidation),
]
}
}
@@ -0,0 +1,165 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import XCTest
import OpenSSL
@testable import NIO
@testable import NIOOpenSSL
class TLSConfigurationTest: XCTestCase {
static var cert1: OpenSSLCertificate!
static var key1: OpenSSLPrivateKey!
static var cert2: OpenSSLCertificate!
static var key2: OpenSSLPrivateKey!
override class func setUp() {
super.setUp()
var (cert, key) = generateSelfSignedCert()
TLSConfigurationTest.cert1 = cert
TLSConfigurationTest.key1 = key
(cert, key) = generateSelfSignedCert()
TLSConfigurationTest.cert2 = cert
TLSConfigurationTest.key2 = key
}
func assertHandshakeError(withClientConfig clientConfig: TLSConfiguration,
andServerConfig serverConfig: TLSConfiguration,
errorTextContains message: String) throws {
return try assertHandshakeError(withClientConfig: clientConfig,
andServerConfig: serverConfig,
errorTextContainsAnyOf: [message])
}
func assertHandshakeError(withClientConfig clientConfig: TLSConfiguration,
andServerConfig serverConfig: TLSConfiguration,
errorTextContainsAnyOf messages: [String]) throws {
let clientContext = try SSLContext(configuration: clientConfig)
let serverContext = try SSLContext(configuration: serverConfig)
let group = try MultiThreadedEventLoopGroup(numThreads: 1)
defer {
try! group.syncShutdownGracefully()
}
let eventHandler = EventRecorderHandler<TLSUserEvent>()
let serverChannel = try serverTLSChannel(withContext: serverContext, andHandlers: [], onGroup: group)
let clientChannel = try clientTLSChannel(withContext: clientContext, preHandlers:[], postHandlers: [eventHandler], onGroup: group, connectingTo: serverChannel.localAddress!)
// We expect the channel to be closed fairly swiftly as the handshake should fail.
clientChannel.closeFuture.whenComplete { _ in
let errors: [OpenSSLError] = eventHandler.events.map {
switch $0 {
case .UserEvent(.handshakeFailed(let err)):
return err
default:
return nil
}
}.flatMap { $0 }
XCTAssertEqual(errors.count, 1)
switch errors[0] {
case .sslError(let errs):
XCTAssertEqual(errs.count, 1)
let correctError: Bool = messages.map { errs[0].description.contains($0) }.reduce(false) { $0 || $1 }
XCTAssert(correctError, errs[0].description)
default:
XCTFail("Unexpected error: \(errors[0])")
}
}
try clientChannel.closeFuture.wait()
}
func testNonOverlappingTLSVersions() throws {
let clientConfig = TLSConfiguration.forClient(minimumTLSVersion: .tlsv11, trustRoots: .certificates([TLSConfigurationTest.cert1]))
let serverConfig = TLSConfiguration.forServer(certificateChain: [.certificate(TLSConfigurationTest.cert1)],
privateKey: .privateKey(TLSConfigurationTest.key1),
maximumTLSVersion: .tlsv1)
try assertHandshakeError(withClientConfig: clientConfig,
andServerConfig: serverConfig,
errorTextContainsAnyOf: ["unsupported protocol", "wrong ssl version"])
}
func testNonOverlappingCipherSuites() throws {
let clientConfig = TLSConfiguration.forClient(cipherSuites: "AES128", trustRoots: .certificates([TLSConfigurationTest.cert1]))
let serverConfig = TLSConfiguration.forServer(certificateChain: [.certificate(TLSConfigurationTest.cert1)],
privateKey: .privateKey(TLSConfigurationTest.key1),
cipherSuites: "AES256")
try assertHandshakeError(withClientConfig: clientConfig, andServerConfig: serverConfig, errorTextContains: "handshake failure")
}
func testCannotVerifySelfSigned() throws {
let clientConfig = TLSConfiguration.forClient()
let serverConfig = TLSConfiguration.forServer(certificateChain: [.certificate(TLSConfigurationTest.cert1)],
privateKey: .privateKey(TLSConfigurationTest.key1))
try assertHandshakeError(withClientConfig: clientConfig, andServerConfig: serverConfig, errorTextContains: "certificate verify failed")
}
func testServerCannotValidateClient() throws {
let clientConfig = TLSConfiguration.forClient(trustRoots: .certificates([TLSConfigurationTest.cert1]),
certificateChain: [.certificate(TLSConfigurationTest.cert2)],
privateKey: .privateKey(TLSConfigurationTest.key2))
let serverConfig = TLSConfiguration.forServer(certificateChain: [.certificate(TLSConfigurationTest.cert1)],
privateKey: .privateKey(TLSConfigurationTest.key1),
certificateVerification: true)
try assertHandshakeError(withClientConfig: clientConfig, andServerConfig: serverConfig, errorTextContains: "alert unknown ca")
}
func testMutualValidation() throws {
let clientConfig = TLSConfiguration.forClient(trustRoots: .certificates([TLSConfigurationTest.cert1]),
certificateChain: [.certificate(TLSConfigurationTest.cert2)],
privateKey: .privateKey(TLSConfigurationTest.key2))
let serverConfig = TLSConfiguration.forServer(certificateChain: [.certificate(TLSConfigurationTest.cert1)],
privateKey: .privateKey(TLSConfigurationTest.key1),
certificateVerification: true,
trustRoots: .certificates([TLSConfigurationTest.cert2]))
let clientContext = try SSLContext(configuration: clientConfig)
let serverContext = try SSLContext(configuration: serverConfig)
let group = try MultiThreadedEventLoopGroup(numThreads: 1)
defer {
try! group.syncShutdownGracefully()
}
let eventHandler = EventRecorderHandler<TLSUserEvent>()
let serverChannel = try serverTLSChannel(withContext: serverContext, andHandlers: [], onGroup: group)
let clientChannel = try clientTLSChannel(withContext: clientContext, preHandlers: [], postHandlers: [eventHandler], onGroup: group, connectingTo: serverChannel.localAddress!)
// Wait for a successful flush: that indicates the channel is up.
var buf = clientChannel.allocator.buffer(capacity: 5)
buf.write(string: "hello")
// Check that we got a handshakeComplete message indicating mutual validation.
let flushFuture = clientChannel.writeAndFlush(data: IOData(buf))
flushFuture.whenComplete { _ in
let handshakeEvents = eventHandler.events.filter {
switch $0 {
case .UserEvent(.handshakeCompleted):
return true
default:
return false
}
}
XCTAssertEqual(handshakeEvents.count, 1)
}
try flushFuture.wait()
}
}