diff --git a/Sources/CNIOOpenSSL/include/c_nio_openssl.h b/Sources/CNIOOpenSSL/include/c_nio_openssl.h index a93d428de..fe0fd657f 100644 --- a/Sources/CNIOOpenSSL/include/c_nio_openssl.h +++ b/Sources/CNIOOpenSSL/include/c_nio_openssl.h @@ -59,4 +59,46 @@ static inline const GENERAL_NAME *CNIOOpenSSL_sk_GENERAL_NAME_value(STACK_OF(GEN return sk_GENERAL_NAME_value(x, idx); } +static inline int CNIOOpenSSL_SSL_CTX_set_app_data(SSL_CTX *ctx, void *arg) { + return SSL_CTX_set_app_data(ctx, arg); +} + +static inline void *CNIOOpenSSL_SSL_CTX_get_app_data(SSL_CTX *ctx) { + return SSL_CTX_get_app_data(ctx); +} + +// We bring this typedef forward in case it's not present in the version of OpenSSL +// we have. +typedef int (*CNIOOpenSSL_SSL_CTX_alpn_select_cb_func)(SSL *ssl, + const unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg); + +static inline int CNIOOpenSSL_SSL_CTX_set_alpn_protos(SSL_CTX *ctx, + const unsigned char *protos, + unsigned int protos_len) { + #if OPENSSL_VERSION_NUMBER >= 0x10002000L + return SSL_CTX_set_alpn_protos(ctx, protos, protos_len); + #else + return 1; + #endif +} + +static inline void CNIOOpenSSL_SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, + CNIOOpenSSL_SSL_CTX_alpn_select_cb_func cb, + void *arg) { + #if OPENSSL_VERSION_NUMBER >= 0x10002000L + SSL_CTX_set_alpn_select_cb(ctx, cb, arg); + #endif +} + +static inline void CNIOOpenSSL_SSL_get0_alpn_selected(const SSL *ssl, + const unsigned char **data, + unsigned int *len) { + #if OPENSSL_VERSION_NUMBER >= 0x10002000L + SSL_get0_alpn_selected(ssl, data, len); + #endif +} #endif diff --git a/Sources/NIOOpenSSL/OpenSSLHandler.swift b/Sources/NIOOpenSSL/OpenSSLHandler.swift index a96a763ef..e2cfe19f6 100644 --- a/Sources/NIOOpenSSL/OpenSSLHandler.swift +++ b/Sources/NIOOpenSSL/OpenSSLHandler.swift @@ -164,7 +164,8 @@ public class OpenSSLHandler : ChannelInboundHandler, ChannelOutboundHandler { writeDataToNetwork(ctx: ctx, promise: nil) // TODO(cory): This event should probably fire out of the OpenSSL info callback. - ctx.fireUserInboundEventTriggered(event: wrapInboundUserEventOut(TLSUserEvent.handshakeCompleted(negotiatedProtocol: nil))) + let negotiatedProtocol = connection.getAlpnProtocol() + ctx.fireUserInboundEventTriggered(event: wrapInboundUserEventOut(TLSUserEvent.handshakeCompleted(negotiatedProtocol: negotiatedProtocol))) // We need to unbuffer any pending writes. We will have pending writes if the user attempted to write // before we completed the handshake. diff --git a/Sources/NIOOpenSSL/SSLConnection.swift b/Sources/NIOOpenSSL/SSLConnection.swift index e15d25705..61764acb9 100644 --- a/Sources/NIOOpenSSL/SSLConnection.swift +++ b/Sources/NIOOpenSSL/SSLConnection.swift @@ -201,4 +201,16 @@ internal final class SSLConnection { } } } + + func getAlpnProtocol() -> String? { + var protoName = UnsafePointer(bitPattern: 0) + var protoLen: UInt32 = 0 + + CNIOOpenSSL_SSL_get0_alpn_selected(ssl, &protoName, &protoLen) + guard protoLen > 0 else { + return nil + } + + return String(decoding: UnsafeBufferPointer(start: protoName, count: Int(protoLen)), as: UTF8.self) + } } diff --git a/Sources/NIOOpenSSL/SSLContext.swift b/Sources/NIOOpenSSL/SSLContext.swift index 42addde2b..b55943297 100644 --- a/Sources/NIOOpenSSL/SSLContext.swift +++ b/Sources/NIOOpenSSL/SSLContext.swift @@ -36,14 +36,78 @@ fileprivate var initialized: Bool = initializeOpenSSL() } #endif +// This bizarre extension to UnsafeBufferPointer is very useful for handling ALPN identifiers. OpenSSL +// likes to work with them in wire format, so rather than us decoding them we can just encode ours to +// the wire format and then work with them from there. +private extension UnsafeBufferPointer where Element == UInt8 { + func locateAlpnIdentifier(identifier: UnsafeBufferPointer) -> (index: Int, length: Int)? where T == Element { + precondition(identifier.count != 0) + let targetLength = Int(identifier[0]) + + var index = 0 + outerLoop: while index < self.count { + let length = Int(self[index]) + guard index + length + 1 <= self.count else { + // Invalid length of ALPN identifier, no match. + return nil + } + + guard targetLength == length else { + index += length + 1 + continue outerLoop + } + + for innerIndex in 1...length { + guard identifier[innerIndex] == self[index + innerIndex] else { + index += length + 1 + continue outerLoop + } + } + + // Found it + return (index: index + 1, length: length) + } + return nil + } +} + private func verifyCallback(preverifyOk: Int32, ctx: UnsafeMutablePointer?) -> Int32 { // This is a no-op verify callback for use with OpenSSL. return preverifyOk } +private func alpnCallback(ssl: UnsafeMutablePointer?, + out: UnsafeMutablePointer?>?, + outlen: UnsafeMutablePointer?, + in: UnsafePointer?, + inlen: UInt32, + appData: UnsafeMutableRawPointer?) -> Int32 { + // Perform some sanity checks. We don't want NULL pointers around here. + guard let ssl = ssl, let out = out, let outlen = outlen, let `in` = `in` else { + return SSL_TLSEXT_ERR_ALERT_FATAL + } + + // We want to take the SSL pointer and extract the parent Swift object. + let parentCtx = SSL_get_SSL_CTX(ssl)! + let parentPtr = CNIOOpenSSL_SSL_CTX_get_app_data(parentCtx)! + let parentSwiftContext: SSLContext = Unmanaged.fromOpaque(parentPtr).takeUnretainedValue() + + let offeredProtocols = UnsafeBufferPointer(start: `in`, count: Int(inlen)) + guard let (index, length) = parentSwiftContext.alpnSelectCallback(offeredProtocols: offeredProtocols) else { + out.pointee = nil + outlen.pointee = 0 + return SSL_TLSEXT_ERR_ALERT_FATAL + } + + out.pointee = `in` + index + outlen.pointee = UInt8(length) + return SSL_TLSEXT_ERR_OK +} + public final class SSLContext { private let sslContext: UnsafeMutablePointer + private let configuration: TLSConfiguration public init(configuration: TLSConfiguration) throws { precondition(initialized) @@ -141,7 +205,17 @@ public final class SSLContext { } } - sslContext = ctx + if configuration.applicationProtocols.count > 0 { + try SSLContext.setAlpnProtocols(configuration.applicationProtocols, context: ctx) + SSLContext.setAlpnCallback(context: ctx) + } + + self.sslContext = ctx + self.configuration = configuration + + // Always make it possible to get from an SSL_CTX structure back to this. + let ptrToSelf = Unmanaged.passUnretained(self).toOpaque() + CNIOOpenSSL_SSL_CTX_set_app_data(ctx, ptrToSelf) } internal func createConnection() -> SSLConnection? { @@ -151,6 +225,17 @@ public final class SSLContext { return SSLConnection(ssl, parentContext:self) } + fileprivate func alpnSelectCallback(offeredProtocols: UnsafeBufferPointer) -> (index: Int, length: Int)? { + for possibility in configuration.applicationProtocols { + let match = possibility.withUnsafeBufferPointer { + offeredProtocols.locateAlpnIdentifier(identifier: $0) + } + if match != nil { return match } + } + + return nil + } + deinit { SSL_CTX_free(sslContext) } @@ -239,4 +324,21 @@ extension SSLContext { } } + private static func setAlpnProtocols(_ protocols: [[UInt8]], context: UnsafeMutablePointer) throws { + // This copy should be done infrequently, so we don't worry too much about it. + let protoBuf = protocols.reduce([UInt8](), +) + let rc = protoBuf.withUnsafeBufferPointer { + CNIOOpenSSL_SSL_CTX_set_alpn_protos(context, $0.baseAddress!, UInt32($0.count)) + } + + // Annoyingly this function reverses the error convention: 0 is success, non-zero is failure. + if rc != 0 { + let errorStack = OpenSSLError.buildErrorStack() + throw OpenSSLError.failedToSetALPN(errorStack) + } + } + + private static func setAlpnCallback(context: UnsafeMutablePointer) { + CNIOOpenSSL_SSL_CTX_set_alpn_select_cb(context, alpnCallback, nil) + } } diff --git a/Sources/NIOOpenSSL/SSLErrors.swift b/Sources/NIOOpenSSL/SSLErrors.swift index 4d07d707a..a9379d5eb 100644 --- a/Sources/NIOOpenSSL/SSLErrors.swift +++ b/Sources/NIOOpenSSL/SSLErrors.swift @@ -69,6 +69,7 @@ public enum OpenSSLError: Error { case unknownError(OpenSSLErrorStack) case uncleanShutdown case invalidSNIName(OpenSSLErrorStack) + case failedToSetALPN(OpenSSLErrorStack) } extension OpenSSLError: Equatable {} diff --git a/Sources/NIOOpenSSL/TLSConfiguration.swift b/Sources/NIOOpenSSL/TLSConfiguration.swift index e6360329e..c5eb69e41 100644 --- a/Sources/NIOOpenSSL/TLSConfiguration.swift +++ b/Sources/NIOOpenSSL/TLSConfiguration.swift @@ -72,6 +72,20 @@ public let defaultCipherSuites = [ "!MD5", ].joined(separator: ":") +/// Encodes a string to the wire format of an ALPN identifier. These MUST be ASCII, and so +/// this routine will crash the program if they aren't, as these are always user-supplied +/// strings. +internal func encodeALPNIdentifier(identifier: String) -> [UInt8] { + var encodedIdentifier = [UInt8]() + encodedIdentifier.append(UInt8(identifier.utf8.count)) + + for codePoint in identifier.unicodeScalars { + encodedIdentifier.append(contentsOf: Unicode.ASCII.encode(codePoint)!) + } + + return encodedIdentifier +} + /// Manages configuration of OpenSSL for SwiftNIO programs. /// /// OpenSSL has a number of configuration options that are worth setting. This structure allows @@ -102,13 +116,20 @@ public struct TLSConfiguration { /// The private key associated with the leaf certificate. public let privateKey: OpenSSLPrivateKeySource? + /// The application protocols to use in the connection. Should be an ordered list of ASCII + /// strings representing the ALPN identifiers of the protocols to negotiate. For clients, + /// the protocols will be offered in the order given. For servers, the protocols will be matched + /// against the client's offered protocols in order. + public let applicationProtocols: [[UInt8]] + private init(cipherSuites: String, minimumTLSVersion: TLSVersion, maximumTLSVersion: TLSVersion?, certificateVerification: Bool, trustRoots: OpenSSLTrustRoots, certificateChain: [OpenSSLCertificateSource], - privateKey: OpenSSLPrivateKeySource?) { + privateKey: OpenSSLPrivateKeySource?, + applicationProtocols: [String]) { self.cipherSuites = cipherSuites self.minimumTLSVersion = minimumTLSVersion self.maximumTLSVersion = maximumTLSVersion @@ -116,6 +137,13 @@ public struct TLSConfiguration { self.trustRoots = trustRoots self.certificateChain = certificateChain self.privateKey = privateKey + + var encodedProtocols = [[UInt8]]() + for `protocol` in applicationProtocols { + encodedProtocols.append(encodeALPNIdentifier(identifier: `protocol`)) + } + + self.applicationProtocols = encodedProtocols } /// Create a TLS configuration for use with server-side contexts. @@ -128,14 +156,16 @@ public struct TLSConfiguration { minimumTLSVersion: TLSVersion = .tlsv1, maximumTLSVersion: TLSVersion? = nil, certificateVerification: Bool = false, - trustRoots: OpenSSLTrustRoots = .default) -> TLSConfiguration { + trustRoots: OpenSSLTrustRoots = .default, + applicationProtocols: [String] = []) -> TLSConfiguration { return TLSConfiguration(cipherSuites: cipherSuites, minimumTLSVersion: minimumTLSVersion, maximumTLSVersion: maximumTLSVersion, certificateVerification: certificateVerification, trustRoots: trustRoots, certificateChain: certificateChain, - privateKey: privateKey) + privateKey: privateKey, + applicationProtocols: applicationProtocols) } @@ -149,13 +179,15 @@ public struct TLSConfiguration { certificateVerification: Bool = true, trustRoots: OpenSSLTrustRoots = .default, certificateChain: [OpenSSLCertificateSource] = [], - privateKey: OpenSSLPrivateKeySource? = nil) -> TLSConfiguration { + privateKey: OpenSSLPrivateKeySource? = nil, + applicationProtocols: [String] = []) -> TLSConfiguration { return TLSConfiguration(cipherSuites: cipherSuites, minimumTLSVersion: minimumTLSVersion, maximumTLSVersion: maximumTLSVersion, certificateVerification: certificateVerification, trustRoots: trustRoots, certificateChain: certificateChain, - privateKey: privateKey) + privateKey: privateKey, + applicationProtocols: applicationProtocols) } } diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index a7a7c2112..3717aba2a 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -52,6 +52,7 @@ import XCTest testCase(IdleStateHandlerTest.allTests), testCase(MarkedCircularBufferTests.allTests), testCase(MessageToByteEncoderTest.allTests), + testCase(OpenSSLALPNTest.allTests), testCase(OpenSSLIntegrationTest.allTests), testCase(SSLCertificateTest.allTests), testCase(SSLPrivateKeyTest.allTests), diff --git a/Tests/NIOOpenSSLTests/OpenSSLALPNTest+XCTest.swift b/Tests/NIOOpenSSLTests/OpenSSLALPNTest+XCTest.swift new file mode 100644 index 000000000..94d16a71e --- /dev/null +++ b/Tests/NIOOpenSSLTests/OpenSSLALPNTest+XCTest.swift @@ -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 +// +//===----------------------------------------------------------------------===// +/// +/// OpenSSLALPNTest+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 OpenSSLALPNTest { + + static var allTests : [(String, (OpenSSLALPNTest) -> () throws -> Void)] { + return [ + ("testBasicALPNNegotiation", testBasicALPNNegotiation), + ("testBasicALPNNegotiationPrefersServerPriority", testBasicALPNNegotiationPrefersServerPriority), + ("testBasicALPNNegotiationNoOverlap", testBasicALPNNegotiationNoOverlap), + ("testBasicALPNNegotiationNotOfferedByClient", testBasicALPNNegotiationNotOfferedByClient), + ("testBasicALPNNegotiationNotSupportedByServer", testBasicALPNNegotiationNotSupportedByServer), + ] + } +} + diff --git a/Tests/NIOOpenSSLTests/OpenSSLALPNTest.swift b/Tests/NIOOpenSSLTests/OpenSSLALPNTest.swift new file mode 100644 index 000000000..21d4d0171 --- /dev/null +++ b/Tests/NIOOpenSSLTests/OpenSSLALPNTest.swift @@ -0,0 +1,149 @@ +//===----------------------------------------------------------------------===// +// +// 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 CNIOOpenSSL +import NIO +import NIOTLS +import NIOOpenSSL + +class OpenSSLALPNTest: XCTestCase { + static var cert: OpenSSLCertificate! + static var key: OpenSSLPrivateKey! + + override class func setUp() { + super.setUp() + let (cert, key) = generateSelfSignedCert() + OpenSSLIntegrationTest.cert = cert + OpenSSLIntegrationTest.key = key + } + + private func configuredSSLContextWithAlpnProtocols(protocols: [String]) throws -> NIOOpenSSL.SSLContext { + let config = TLSConfiguration.forServer(certificateChain: [.certificate(OpenSSLIntegrationTest.cert)], + privateKey: .privateKey(OpenSSLIntegrationTest.key), + trustRoots: .certificates([OpenSSLIntegrationTest.cert]), + applicationProtocols: protocols) + return try SSLContext(configuration: config) + } + + private func assertNegotiatedProtocol(protocol: String?, + serverContext: NIOOpenSSL.SSLContext, + clientContext: NIOOpenSSL.SSLContext) throws { + let group = try MultiThreadedEventLoopGroup(numThreads: 1) + defer { + try! group.syncShutdownGracefully() + } + + let completionPromise: Promise = group.next().newPromise() + let serverHandler = EventRecorderHandler() + + let serverChannel = try serverTLSChannel(withContext: serverContext, + andHandlers: [serverHandler, PromiseOnReadHandler(promise: completionPromise)], + onGroup: group) + defer { + _ = try! serverChannel.close().wait() + } + + let clientChannel = try clientTLSChannel(withContext: clientContext, + preHandlers: [], + postHandlers: [], + onGroup: group, + connectingTo: serverChannel.localAddress!) + defer { + _ = try! clientChannel.close().wait() + } + + var originalBuffer = clientChannel.allocator.buffer(capacity: 5) + originalBuffer.write(string: "Hello") + try clientChannel.writeAndFlush(data: NIOAny(originalBuffer)).wait() + _ = try completionPromise.futureResult.wait() + + let expectedEvents: [EventRecorderHandler.RecordedEvents] = [ + .Registered, + .Active, + .UserEvent(TLSUserEvent.handshakeCompleted(negotiatedProtocol: `protocol`)), + .Read, + .ReadComplete + ] + XCTAssertEqual(expectedEvents, serverHandler.events) + } + + func testBasicALPNNegotiation() throws { + let ctx: NIOOpenSSL.SSLContext + do { + ctx = try configuredSSLContextWithAlpnProtocols(protocols: ["h2", "http/1.1"]) + } catch OpenSSLError.failedToSetALPN { + XCTAssertTrue(SSLeay() < 0x010002000) + return + } + + try assertNegotiatedProtocol(protocol: "h2", serverContext: ctx, clientContext: ctx) + } + + func testBasicALPNNegotiationPrefersServerPriority() throws { + let serverCtx: NIOOpenSSL.SSLContext + let clientCtx: NIOOpenSSL.SSLContext + do { + serverCtx = try configuredSSLContextWithAlpnProtocols(protocols: ["h2", "http/1.1"]) + clientCtx = try configuredSSLContextWithAlpnProtocols(protocols: ["http/1.1", "h2"]) + } catch OpenSSLError.failedToSetALPN { + XCTAssertTrue(SSLeay() < 0x010002000) + return + } + + try assertNegotiatedProtocol(protocol: "h2", serverContext: serverCtx, clientContext: clientCtx) + } + + func testBasicALPNNegotiationNoOverlap() throws { + let serverCtx: NIOOpenSSL.SSLContext + let clientCtx: NIOOpenSSL.SSLContext + do { + serverCtx = try configuredSSLContextWithAlpnProtocols(protocols: ["h2", "http/1.1"]) + clientCtx = try configuredSSLContextWithAlpnProtocols(protocols: ["spdy/3", "webrtc"]) + } catch OpenSSLError.failedToSetALPN { + XCTAssertTrue(SSLeay() < 0x010002000) + return + } + + try assertNegotiatedProtocol(protocol: nil, serverContext: serverCtx, clientContext: clientCtx) + } + + func testBasicALPNNegotiationNotOfferedByClient() throws { + let serverCtx: NIOOpenSSL.SSLContext + let clientCtx: NIOOpenSSL.SSLContext + do { + serverCtx = try configuredSSLContextWithAlpnProtocols(protocols: ["h2", "http/1.1"]) + clientCtx = try configuredSSLContextWithAlpnProtocols(protocols: []) + } catch OpenSSLError.failedToSetALPN { + XCTAssertTrue(SSLeay() < 0x010002000) + return + } + + try assertNegotiatedProtocol(protocol: nil, serverContext: serverCtx, clientContext: clientCtx) + } + + func testBasicALPNNegotiationNotSupportedByServer() throws { + let serverCtx: NIOOpenSSL.SSLContext + let clientCtx: NIOOpenSSL.SSLContext + do { + serverCtx = try configuredSSLContextWithAlpnProtocols(protocols: []) + clientCtx = try configuredSSLContextWithAlpnProtocols(protocols: ["h2", "http/1.1"]) + } catch OpenSSLError.failedToSetALPN { + XCTAssertTrue(SSLeay() < 0x010002000) + return + } + + try assertNegotiatedProtocol(protocol: nil, serverContext: serverCtx, clientContext: clientCtx) + } +} diff --git a/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift b/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift index 3b9f45ad5..dd6f9aa54 100644 --- a/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift +++ b/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift @@ -35,7 +35,7 @@ private final class SimpleEchoServer: ChannelInboundHandler { } } -private final class PromiseOnReadHandler: ChannelInboundHandler { +internal final class PromiseOnReadHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer public typealias OutboundOut = ByteBuffer public typealias InboundUserEventIn = TLSUserEvent