diff --git a/Sources/NIO/ByteBuffer-foundation.swift b/Sources/NIO/ByteBuffer-foundation.swift index ac97bbb6c..f7dd00aff 100644 --- a/Sources/NIO/ByteBuffer-foundation.swift +++ b/Sources/NIO/ByteBuffer-foundation.swift @@ -51,4 +51,11 @@ extension ByteBuffer { deallocator: .custom { _, _ in storageRef.release() }) } } + + public func string(at index: Int, length: Int, encoding: String.Encoding) -> String? { + guard let data = self.data(at: index, length: length) else { + return nil + } + return String(data: data, encoding: encoding) + } } diff --git a/Sources/NIOTLS/SNIHandler.swift b/Sources/NIOTLS/SNIHandler.swift new file mode 100644 index 000000000..0b66a218c --- /dev/null +++ b/Sources/NIOTLS/SNIHandler.swift @@ -0,0 +1,407 @@ +//===----------------------------------------------------------------------===// +// +// 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 NIO + +/// The length of the TLS record header in bytes. +private let tlsRecordHeaderLength = 5 + +/// The content type identifier for a TLS handshake record. +private let tlsContentTypeHandshake: UInt8 = 22 + +/// The handshake type identifier for ClientHello records. +private let handshakeTypeClientHello: UInt8 = 1 + +/// The extension type for the SNI extension. +private let sniExtensionType: UInt16 = 0 + +/// The ServerName type for DNS host names. +private let sniHostNameType: UInt8 = 0 + +/// The result of the SNI parsing. If `hostname`, then the enum also +/// contains the hostname received in the SNI extension. If `fallback`, +/// then either we could not parse the SNI extension or it was not there +/// at all. +public enum SniResult: Equatable { + case fallback + case hostname(String) + + public static func ==(lhs: SniResult, rhs: SniResult) -> Bool { + switch (lhs, rhs) { + case (.fallback, .fallback): + return true + case (.hostname(let s1), .hostname(let s2)): + return s1 == s2 + default: + return false + } + } +} + +private enum InternalSniErrors: Error { + case invalidLengthInRecord + case invalidRecord + case recordIncomplete +} + +private extension ByteBuffer { + mutating func moveReaderIndexIfPossible(forwardBy distance: Int) throws { + guard self.readableBytes >= distance else { + throw InternalSniErrors.invalidLengthInRecord + } + self.moveReaderIndex(forwardBy: distance) + } + + mutating func readIntegerIfPossible() throws -> T { + guard let integer: T = self.readInteger() else { + throw InternalSniErrors.invalidLengthInRecord + } + return integer + } +} + +/// A channel handler that can be used to arbitrarily edit a channel +/// pipeline based on the hostname requested in the Server Name Indication +/// portion of the TLS Client Hello. +/// +/// This handler is most commonly used when configuring TLS, to control +/// which certificates are going to be shown to the client. It can also be used +/// to ensure that only the resources required to serve a given virtual host are +/// actually present in the channel pipeline. +/// +/// This handler does not depend on any specific TLS implementation. Instead, it parses +/// the Client Hello itself, directly. This allows it to be generic across all possible +/// TLS backends that can be used with NIO. It also allows for the pipeline change to +/// be done asynchronously, providing more flexibility about how the user configures the +/// pipeline. +public class SniHandler: ByteToMessageDecoder { + public var cumulationBuffer: ByteBuffer? + public typealias InboundIn = ByteBuffer + public typealias InboundOut = ByteBuffer + + private let completionHandler: (SniResult) -> Future + private var waitingForUser: Bool + + public init(sniCompleteHandler: @escaping (SniResult) -> Future) { + self.cumulationBuffer = nil + self.completionHandler = sniCompleteHandler + self.waitingForUser = false + } + + // A note to maintainers: this method *never* returns true. + public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> Bool { + // If we've asked the user to mutate the pipeline already, we're not interested in + // this data. Keep waiting. + if waitingForUser { + return false + } + + let serverName: String? + do { + serverName = try parseTLSDataForServerName(buffer: buffer) + } catch InternalSniErrors.recordIncomplete { + // Nothing bad here, we just don't have enough data. + return false + } catch { + // Some error occurred. Fall back and let the TLS stack + // handle it. + sniComplete(result: .fallback, ctx: ctx) + return false + } + + if let serverName = serverName { + sniComplete(result: .hostname(serverName), ctx: ctx) + } else { + sniComplete(result: .fallback, ctx: ctx) + } + return false + } + + /// Given a buffer of data that may contain a TLS Client Hello, parses the buffer looking for + /// a server name extension. If it can be found, returns the host name in that extension. If + /// no host name or extension is present, returns nil. If an error is encountered, throws. If + /// there is not enough data in the buffer yet, throws recordIncomplete. + private func parseTLSDataForServerName(buffer: ByteBuffer) throws -> String? { + // We're taking advantage of value semantics here: this copy of the buffer will reference + // the same underlying storage as the one we were passed, but any changes to it will not + // be reflected in the outer buffer. That saves us from needing to maintain offsets + // manually in this code. Thanks, Swift! + var tempBuffer = buffer + + // First, parse the header. + let contentLength = try parseRecordHeader(buffer: &tempBuffer) + guard buffer.readableBytes >= contentLength else { + throw InternalSniErrors.recordIncomplete + } + + // At this point we know we have enough, at least according to the outer layer. We now want to + // take a slice of our temp buffer so that we can make confident assertions about + // all of the length. This also prevents us messing stuff up. + // + // From this point onwards if we don't have enough data to satisfy a read, this is an error and + // we will fall back to let the upper layers handle it. + tempBuffer = tempBuffer.slice(at: tempBuffer.readerIndex, length: Int(contentLength))! + + // Now parse the handshake header. If the length of the handshake message is not exactly the + // length of this record, something has gone wrong and we should give up. + let handshakeLength = try parseHandshakeHeader(buffer: &tempBuffer) + guard tempBuffer.readableBytes == handshakeLength else { + throw InternalSniErrors.invalidRecord + } + + // Now parse the client hello header. If the remaining length, which should be entirely extensions, + // is not exactly the length of this record, something has gone wrong and we should give up. + let extensionsLength = try parseClientHelloHeader(buffer: &tempBuffer) + guard tempBuffer.readableBytes == extensionsLength else { + throw InternalSniErrors.invalidLengthInRecord + } + + return try parseExtensionsForServerName(buffer: &tempBuffer) + } + + /// Parses the TLS Record Header, ensuring that this is a handshake record and that + /// the basics of the data appear to be correct. + /// + /// Returns the content-length of the record. + private func parseRecordHeader(buffer: inout ByteBuffer) throws -> Int { + // First, the obvious check: are there enough bytes for us to parse a complete + // header? Because of this check we can use unsafe integer reads in the rest of + // this function, as we'll only ever read tlsRecordHeaderLength number of bytes + // here. + guard buffer.readableBytes >= tlsRecordHeaderLength else { + throw InternalSniErrors.recordIncomplete + } + + // Check the content type. + let contentType: UInt8 = buffer.readInteger()! + guard contentType == tlsContentTypeHandshake else { + // Whatever this is, it's not a handshake message, so something has gone + // wrong. We're going to fall back to the default handler here and let + // that handler try to clean up this mess. + throw InternalSniErrors.invalidRecord + } + + // Now, check the major version. + let majorVersion: UInt8 = buffer.readInteger()! + guard majorVersion == 3 else { + // A major version of 3 is the major version used for SSLv3 and all subsequent versions + // of the protocol. If that's not what this is, we don't know what's happening here. + // Again, let the default handler make sense of this. + throw InternalSniErrors.invalidRecord + } + + // Skip the minor version byte, then grab the content length. + buffer.moveReaderIndex(forwardBy: 1) + let contentLength: UInt16 = buffer.readInteger()! + return Int(contentLength) + } + + /// Parses the header of a TLS Handshake Record. Returns the expected number + /// of bytes in the handshake body, or throws if this is not a ClientHello or + /// has some other problem. + private func parseHandshakeHeader(buffer: inout ByteBuffer) throws -> Int { + // Ok, we're looking at a handshake message. That looks like this: + // (see https://tools.ietf.org/html/rfc5246#section-7.4). + // + // struct { + // HandshakeType msg_type; /* handshake type */ + // uint24 length; /* bytes in message */ + // select (HandshakeType) { + // case hello_request: HelloRequest; + // case client_hello: ClientHello; + // case server_hello: ServerHello; + // case certificate: Certificate; + // case server_key_exchange: ServerKeyExchange; + // case certificate_request: CertificateRequest; + // case server_hello_done: ServerHelloDone; + // case certificate_verify: CertificateVerify; + // case client_key_exchange: ClientKeyExchange; + // case finished: Finished; + // } body; + // } Handshake; + // + // For the sake of our own sanity, we should check the handshake type and + // validate its length. uint24 is a stupid type, so we have to play some + // games here to get this to work. If we check that we have 4 bytes up-front + // we can use unsafe reads: fewer than 4 bytes makes this message bogus. + guard buffer.readableBytes >= 4 else { + throw InternalSniErrors.invalidRecord + } + + let handshakeTypeAndLength: UInt32 = buffer.readInteger()! + let handshakeType: UInt8 = UInt8((handshakeTypeAndLength & 0xFF000000) >> 24) + let handshakeLength: UInt32 = handshakeTypeAndLength & 0x00FFFFFF + guard handshakeType == handshakeTypeClientHello else { + throw InternalSniErrors.invalidRecord + } + + return Int(handshakeLength) + } + + /// Parses the header of the Client Hello record, and returns the total number of bytes + /// used for extensions, or throws if the header is invalid or corrupted in some way. + private func parseClientHelloHeader(buffer: inout ByteBuffer) throws -> Int { + // Ok dear reader, you've made it this far, now you get to see the true face of the + // ClientHello record. For context, this comes from + // https://tools.ietf.org/html/rfc5246#section-7.4.1.2 + // + // struct { + // ProtocolVersion client_version; + // Random random; + // SessionID session_id; + // CipherSuite cipher_suites<2..2^16-2>; + // CompressionMethod compression_methods<1..2^8-1>; + // select (extensions_present) { + // case false: + // struct {}; + // case true: + // Extension extensions<0..2^16-1>; + // }; + // } ClientHello; + // + // We want to go straight down to the extensions, but we can't do that because + // the SessionID, CipherSuite and CompressionMethod fields are variable length. + // So we skip to them, and then parse. The ProtocolVersion field is two bytes: + // the Random field is a 32-bit integer timestamp followed by a 28-byte array, + // totalling 32 bytes. All-in-all we want to skip forward 34 bytes. + // Unlike in other parsing methods we don't do an explicit length check here + // because we don't know how long these fields are supposed to be: all we do know + // is that the size of the ByteBuffer provides an upper bound on the size of this + // header, so we use safe reads which will throw if the buffer is too short. + try buffer.moveReaderIndexIfPossible(forwardBy: 34) + + let sessionIDLength: UInt8 = try buffer.readIntegerIfPossible() + try buffer.moveReaderIndexIfPossible(forwardBy: Int(sessionIDLength)) + + let cipherSuitesLength: UInt16 = try buffer.readIntegerIfPossible() + try buffer.moveReaderIndexIfPossible(forwardBy: Int(cipherSuitesLength)) + + let compressionMethodLength: UInt8 = try buffer.readIntegerIfPossible() + try buffer.moveReaderIndexIfPossible(forwardBy: Int(compressionMethodLength)) + + // Ok, we're at the extensions! Return the length. + let extensionsLength: UInt16 = try buffer.readIntegerIfPossible() + return Int(extensionsLength) + } + + /// Parses the extensions portion of a Client Hello looking for a ServerName extension. + /// Returns the host name in the ServerName extension, if any. If there is invalid data, + /// throws. If no host name can be found, either due to the ServerName extension not containing + /// one or due to no such extension being present, returns nil. + private func parseExtensionsForServerName(buffer: inout ByteBuffer) throws -> String? { + // The minimum number of bytes in an extension is 4: if we have fewer than that + // we're done. + while buffer.readableBytes >= 4 { + let extensionType: UInt16 = try buffer.readIntegerIfPossible() + let extensionLength: UInt16 = try buffer.readIntegerIfPossible() + + guard buffer.readableBytes >= extensionLength else { + throw InternalSniErrors.invalidLengthInRecord + } + + guard extensionType == sniExtensionType else { + // Move forward by the length of this extension. + try buffer.moveReaderIndexIfPossible(forwardBy: Int(extensionLength)) + continue + } + + // We've found the server name extension. It's possible a malicious client could attempt a confused + // deputy attack by giving us contradictory lengths, so we again want to trim the bytebuffer down + // so that we never read past the advertised length of this extension. + buffer = buffer.slice(at: buffer.readerIndex, length: Int(extensionLength))! + return try parseServerNameExtension(buffer: &buffer) + } + return nil + } + + /// Parses a ServerName extension and returns the host name contained within, if any. If the extension + /// is invalid for any reason, this will throw. If the extension does not contain a hostname, returns + /// nil. + private func parseServerNameExtension(buffer: inout ByteBuffer) throws -> String? { + // The format of the SNI extension is here: https://tools.ietf.org/html/rfc6066#page-6 + // + // struct { + // NameType name_type; + // select (name_type) { + // case host_name: HostName; + // } name; + // } ServerName; + // + // enum { + // host_name(0), (255) + // } NameType; + // + // opaque HostName<1..2^16-1>; + // + // struct { + // ServerName server_name_list<1..2^16-1> + // } ServerNameList; + // + // Note, however, that this is pretty academic. The SNI extension forbids multiple entries + // in the ServerNameList that have the same NameType. As only one NameType is defined, we + // could safely assume this list is one entry long. + // + // HOWEVER! It is a bad idea to write code that assumes that an extension point will + // never be used, so let's try to parse this properly. We're going to parse only until we + // find a host_name entry. + // + // This also uses unsafe reads: at this point, if the buffer is short then we're screwed. + let nameBufferLength: UInt16 = try buffer.readIntegerIfPossible() + guard buffer.readableBytes >= nameBufferLength else { + throw InternalSniErrors.invalidLengthInRecord + } + + // We are never looking for another extension, so this is now all that we care about in the + // world. Slice our way down to just that. + buffer = buffer.slice(at: buffer.readerIndex, length: Int(nameBufferLength))! + while buffer.readableBytes > 0 { + let nameType: UInt8 = try buffer.readIntegerIfPossible() + + // From the RFC: + // "For backward compatibility, all future data structures associated with new NameTypes + // MUST begin with a 16-bit length field." + let nameLength: UInt16 = try buffer.readIntegerIfPossible() + guard nameType == sniHostNameType else { + try buffer.moveReaderIndexIfPossible(forwardBy: Int(nameLength)) + continue + } + + guard let hostname = buffer.string(at: buffer.readerIndex, length: Int(nameLength), encoding: .ascii) else { + throw InternalSniErrors.invalidRecord + } + return hostname + } + return nil + } + + /// Called when we either know the hostname being queried, or we know we can't + /// work it out. Either way, we're done now. + /// + /// The processing here is as follows: + /// + /// 1. Call the user back with the result of the SNI lookup. At this point we're going to + /// allow them to tweak the channel pipeline as they see fit. + /// 2. Wait for them to complete. In this time, we will continue to buffer all inbound + /// data. + /// 3. When the user completes, remove ourselves from the pipeline. This will trigger the + /// ByteToMessageDecoder to automatically deliver the buffered bytes to the next handler + /// in the pipeline, which is now responsible for the work. + private func sniComplete(result: SniResult, ctx: ChannelHandlerContext) { + waitingForUser = true + _ = completionHandler(result).then { + ctx.pipeline?.remove(handler: self) + } + } +} diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 03f7d70e9..6d0a5cb62 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -25,6 +25,7 @@ import XCTest #if os(Linux) || os(FreeBSD) @testable import NIOHTTP1Tests @testable import NIOOpenSSLTests + @testable import NIOTLSTests @testable import NIOTests XCTMain([ @@ -51,6 +52,7 @@ import XCTest testCase(OpenSSLIntegrationTest.allTests), testCase(SSLCertificateTest.allTests), testCase(SSLPrivateKeyTest.allTests), + testCase(SniHandlerTest.allTests), testCase(SocketAddressTest.allTests), testCase(TLSConfigurationTest.allTests), testCase(TypeAssistedChannelHandlerTest.allTests), diff --git a/Tests/NIOTLSTests/SNIHandlerTests+XCTest.swift b/Tests/NIOTLSTests/SNIHandlerTests+XCTest.swift new file mode 100644 index 000000000..b123eac40 --- /dev/null +++ b/Tests/NIOTLSTests/SNIHandlerTests+XCTest.swift @@ -0,0 +1,61 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +/// +/// SniHandlerTests+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 SniHandlerTest { + + static var allTests : [(String, (SniHandlerTest) -> () throws -> Void)] { + return [ + ("testLibre227NoSniDripFeed", testLibre227NoSniDripFeed), + ("testLibre227WithSniDripFeed", testLibre227WithSniDripFeed), + ("testOpenSSL102NoSniDripFeed", testOpenSSL102NoSniDripFeed), + ("testOpenSSL102WithSniDripFeed", testOpenSSL102WithSniDripFeed), + ("testCurlSecureTransportDripFeed", testCurlSecureTransportDripFeed), + ("testSafariDripFeed", testSafariDripFeed), + ("testChromeDripFeed", testChromeDripFeed), + ("testFirefoxDripFeed", testFirefoxDripFeed), + ("testLibre227NoSniBlast", testLibre227NoSniBlast), + ("testLibre227WithSniBlast", testLibre227WithSniBlast), + ("testOpenSSL102NoSniBlast", testOpenSSL102NoSniBlast), + ("testOpenSSL102WithSniBlast", testOpenSSL102WithSniBlast), + ("testCurlSecureTransportBlast", testCurlSecureTransportBlast), + ("testSafariBlast", testSafariBlast), + ("testChromeBlast", testChromeBlast), + ("testFirefoxBlast", testFirefoxBlast), + ("testIgnoresUnknownRecordTypes", testIgnoresUnknownRecordTypes), + ("testIgnoresUnknownTlsVersions", testIgnoresUnknownTlsVersions), + ("testIgnoresNonClientHelloHandshakeMessages", testIgnoresNonClientHelloHandshakeMessages), + ("testIgnoresInvalidHandshakeLength", testIgnoresInvalidHandshakeLength), + ("testIgnoresInvalidCipherSuiteLength", testIgnoresInvalidCipherSuiteLength), + ("testIgnoresInvalidCompressionLength", testIgnoresInvalidCompressionLength), + ("testIgnoresInvalidExtensionLength", testIgnoresInvalidExtensionLength), + ("testIgnoresInvalidIndividualExtensionLength", testIgnoresInvalidIndividualExtensionLength), + ("testIgnoresUnknownNameType", testIgnoresUnknownNameType), + ("testIgnoresInvalidNameLength", testIgnoresInvalidNameLength), + ("testIgnoresInvalidNameExtensionLength", testIgnoresInvalidNameExtensionLength), + ("testQuiteTruncatedPacket", testQuiteTruncatedPacket), + ("testLudicrouslyTruncatedPacket", testLudicrouslyTruncatedPacket), + ] + } +} + diff --git a/Tests/NIOTLSTests/SNIHandlerTests.swift b/Tests/NIOTLSTests/SNIHandlerTests.swift new file mode 100644 index 000000000..3d1744655 --- /dev/null +++ b/Tests/NIOTLSTests/SNIHandlerTests.swift @@ -0,0 +1,464 @@ +//===----------------------------------------------------------------------===// +// +// 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 +@testable import NIO +import NIOTLS + +private let libressl227HelloNoSni = """ +FgMBATkBAAE1AwNqcHrXsRJKtLx2HC1BXLt+kAk7SnCMk8qK +QPmv7L3u7QAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq +ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA +AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx +wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI +ABYAE8ANwAMACgAVABIACQD/AQAAdAALAAQDAAECAAoAOgA4 +AA4ADQAZABwACwAMABsAGAAJAAoAGgAWABcACAAGAAcAFAAV +AAQABQASABMAAQACAAMADwAQABEAIwAAAA0AJgAkBgEGAgYD +7+8FAQUCBQMEAQQCBAPu7u3tAwEDAgMDAgECAgID +""" + +private let libressl227HelloWithSni = """ +FgMBAU0BAAFJAwN/gCauChg0p2XhDp6z2+gRqMeyb5zfxBOW +dtGXsknrcAAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq +ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA +AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx +wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI +ABYAE8ANwAMACgAVABIACQD/AQAAiAAAABAADgAAC2h0dHBi +aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY +AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP +ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u +7e0DAQMCAwMCAQICAgM= +""" + +private let openssl102HelloNoSni = """ +FgMBAS8BAAErAwPmgeNB1uuTN/P5ZlOjLQMHjxgIotE2796Z +ILeQHLg/ZQAArMAwwCzAKMAkwBTACgClAKMAoQCfAGsAagBp +AGgAOQA4ADcANgCIAIcAhgCFwDLALsAqwCbAD8AFAJ0APQA1 +AITAL8ArwCfAI8ATwAkApACiAKAAngBnAEAAPwA+ADMAMgAx +ADAAmgCZAJgAlwBFAEQAQwBCwDHALcApwCXADsAEAJwAPAAv +AJYAQQAHwBHAB8AMwAIABQAEwBLACAAWABMAEAANwA3AAwAK +AP8CAQAAVQALAAQDAAECAAoAHAAaABcAGQAcABsAGAAaABYA +DgANAAsADAAJAAoAIwAAAA0AIAAeBgEGAgYDBQEFAgUDBAEE +AgQDAwEDAgMDAgECAgIDAA8AAQE= +""" + +private let openssl102HelloWithSni = """ +FgMBAUMBAAE/AwO0rkxuVnE+GcBdNP2UJwTCVSi2H2NbIngp +eTzpoVc+kgAArMAwwCzAKMAkwBTACgClAKMAoQCfAGsAagBp +AGgAOQA4ADcANgCIAIcAhgCFwDLALsAqwCbAD8AFAJ0APQA1 +AITAL8ArwCfAI8ATwAkApACiAKAAngBnAEAAPwA+ADMAMgAx +ADAAmgCZAJgAlwBFAEQAQwBCwDHALcApwCXADsAEAJwAPAAv +AJYAQQAHwBHAB8AMwAIABQAEwBLACAAWABMAEAANwA3AAwAK +AP8CAQAAaQAAABAADgAAC2h0dHBiaW4ub3JnAAsABAMAAQIA +CgAcABoAFwAZABwAGwAYABoAFgAOAA0ACwAMAAkACgAjAAAA +DQAgAB4GAQYCBgMFAQUCBQMEAQQCBAMDAQMCAwMCAQICAgMA +DwABAQ== +""" + +private let curlWithSecureTransport = """ +FgMBAL4BAAC6AwNZ54sY4KDX3NJ7JTk/ER+MdC3dT72bCG8P +wFcIw08qJAAARAD/wCzAK8AkwCPACsAJwAjAMMAvwCjAJ8AU +wBPAEgCfAJ4AawBnADkAMwAWAJ0AnAA9ADwANQAvAAoArwCu +AI0AjACLAQAATQAAABAADgAAC2h0dHBiaW4ub3JnAAoACAAG +ABcAGAAZAAsAAgEAAA0AEgAQBAECAQUBBgEEAwIDBQMGAwAF +AAUBAAAAAAASAAAAFwAA +""" + +private let safariWithSecureTransport = """ +FgMBAOEBAADdAwP1UKyAyXfMC35xny6EHejdgPt7aPoHdeQG +/1FuKmniSQAAKMAswCvAJMAjwArACcypwDDAL8AowCfAFMAT +zKgAnQCcAD0APAA1AC8BAACM/wEAAQAAAAAQAA4AAAtodHRw +YmluLm9yZwAXAAAADQAUABIEAwgEBAEFAwgFBQEIBgYBAgEA +BQAFAQAAAAAzdAAAABIAAAAQADAALgJoMgVoMi0xNgVoMi0x +NQVoMi0xNAhzcGR5LzMuMQZzcGR5LzMIaHR0cC8xLjEACwAC +AQAACgAIAAYAHQAXABg= +""" + +private let chromeWithBoringSSL = """ +FgMBAMIBAAC+AwMTXqvA3thIWxHtp1Fpf56+YmWbfaNxMO4f +DSUKnu6d/gAAHBoawCvAL8AswDDMqcyowBPAFACcAJ0ALwA1 +AAoBAAB5qqoAAP8BAAEAAAAAEAAOAAALaHR0cGJpbi5vcmcA +FwAAACMAAAANABQAEgQDCAQEAQUDCAUFAQgGBgECAQAFAAUB +AAAAAAASAAAAEAAOAAwCaDIIaHR0cC8xLjF1UAAAAAsAAgEA +AAoACgAIWloAHQAXABjKygABAA== +""" + +private let firefoxWithNSS = """ +FgMBALcBAACzAwN6qgxS1T0PTzYdLZ+3CvMBosugW1anTOsO +blZjJ+/adgAAHsArwC/MqcyowCzAMMAKwAnAE8AUADMAOQAv +ADUACgEAAGwAAAAQAA4AAAtodHRwYmluLm9yZwAXAAD/AQAB +AAAKAAoACAAdABcAGAAZAAsAAgEAACMAAAAQAA4ADAJoMgho +dHRwLzEuMQAFAAUBAAAAAAANABgAFgQDBQMGAwgECAUIBgQB +BQEGAQIDAgE= +""" + +private let alertFatalInternalError = "FQMDAAICUA==" + +private let invalidTlsVersion = """ +FgQAALcBAACzAwN6qgxS1T0PTzYdLZ+3CvMBosugW1anTOsO +blZjJ+/adgAAHsArwC/MqcyowCzAMMAKwAnAE8AUADMAOQAv +ADUACgEAAGwAAAAQAA4AAAtodHRwYmluLm9yZwAXAAD/AQAB +AAAKAAoACAAdABcAGAAZAAsAAgEAACMAAAAQAA4ADAJoMgho +dHRwLzEuMQAFAAUBAAAAAAANABgAFgQDBQMGAwgECAUIBgQB +BQEGAQIDAgE= +""" + +private let clientKeyExchange = """ +FgMDAJYQAACSkQQAR/1YL9kZ13n6OWVy6VMLqc++ZTHfZVlt +RlLYoziZSu7tKZ9UUMvZJ5BCcH3juFGM9wftZi0PIjKuRrBZ +erk++KawYtxuaIwDGwinj70hmUxB9jQSa0M9NXXNVHZWgMSX +YVj3N8SBAfmGbWQbH9uONzieFuVYwkmVEidIlE7A04gHP9id +Oy5Badfl6Ab5fDg= +""" + +private let invalidHandshakeLength = """ +FgMBALcBAQCzAwN6qgxS1T0PTzYdLZ+3CvMBosugW1anTOsO +blZjJ+/adgAAHsArwC/MqcyowCzAMMAKwAnAE8AUADMAOQAv +ADUACgEAAGwAAAAQAA4AAAtodHRwYmluLm9yZwAXAAD/AQAB +AAAKAAoACAAdABcAGAAZAAsAAgEAACMAAAAQAA4ADAJoMgho +dHRwLzEuMQAFAAUBAAAAAAANABgAFgQDBQMGAwgECAUIBgQB +BQEGAQIDAgE= +""" + +private let invalidCipherSuitesLength = """ +FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U/ +lEvy1/7zGQDw/8wUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq +ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA +AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx +wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI +ABYAE8ANwAMACgAVABIACQD/AQAAiAAAABAADgAAC2h0dHBi +aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY +AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP +ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u +7e0DAQMCAwMCAQICAgM= +""" + +private let invalidCompressionLength = """ +'FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U +/lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawB +qADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQD +AAITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMA +xwC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsA +IABYAE8ANwAMACgAVABIACQD//wAAiAAAABAADgAAC2h0dHB +iaW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwA +YAAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwA +PABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7 +u7e0DAQMCAwMCAQICAgM=' +""" + +private let invalidExtensionLength = """ +FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U/ +lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq +ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA +AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx +wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI +ABYAE8ANwAMACgAVABIACQD/AQDw/wAAABAADgAAC2h0dHBi +aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY +AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP +ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u +7e0DAQMCAwMCAQICAgM= +""" + +private let invalidIndividualExtensionLength = """ +FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U/ +lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq +ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA +AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx +wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI +ABYAE8ANwAMACgAVABIACQD/AQAAiAAA8P8ADgAAC2h0dHBi +aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY +AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP +ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u +7e0DAQMCAwMCAQICAgM= +""" + +private let unknownNameType = """ +'FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U +/lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawB +qADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQD +AAITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMA +xwC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsA +IABYAE8ANwAMACgAVABIACQD/AQAAiAAAABAADgEAC2h0dHB +iaW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwA +YAAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwA +PABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7 +u7e0DAQMCAwMCAQICAgM= +""" + +private let invalidNameLength = """ +FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U/ +lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq +ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA +AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx +wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI +ABYAE8ANwAMACgAVABIACQD/AQAAiAAAABAADgD/8Gh0dHBi +aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY +AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP +ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u +7e0DAQMCAwMCAQICAgM= +""" + +private let invalidNameExtensionLength = """ +FgMBAU0BAAFJAwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oWq6U/ +lEvy1/7zGQAAmMwUzBPMFcAwwCzAKMAkwBTACgCjAJ8AawBq +ADkAOP+FAMQAwwCIAIcAgcAywC7AKsAmwA/ABQCdAD0ANQDA +AITAL8ArwCfAI8ATwAkAogCeAGcAQAAzADIAvgC9AEUARMAx +wC3AKcAlwA7ABACcADwALwC6AEHAEcAHwAzAAgAFAATAEsAI +ABYAE8ANwAMACgAVABIACQD/AQAAiAAAABDw/wAAC2h0dHBi +aW4ub3JnAAsABAMAAQIACgA6ADgADgANABkAHAALAAwAGwAY +AAkACgAaABYAFwAIAAYABwAUABUABAAFABIAEwABAAIAAwAP +ABAAEQAjAAAADQAmACQGAQYCBgPv7wUBBQIFAwQBBAIEA+7u +7e0DAQMCAwMCAQICAgM= +""" + +private let quiteTruncatedPacket = """ +FgMBACsBAAAneDI3AwNyvld+G6aaYHyOf2Q6A5P7pFYdY9oW +q6U/lEvy1/7zGQ== +""" + +private let ludicrouslyTruncatedPacket = "FgMBAAEB" + +private extension ChannelPipeline { + func contains(handler: ChannelHandler) throws -> Bool { + do { + let _ = try self.context(handler: handler).wait() + return true + } catch ChannelPipelineError.notFound { + return false + } + } + func assertDoesNotContain(handler: ChannelHandler) throws { + XCTAssertFalse(try contains(handler: handler)) + } + + func assertContains(handler: ChannelHandler) throws { + XCTAssertTrue(try contains(handler: handler)) + } +} + + +class SniHandlerTest: XCTestCase { + private func bufferForBase64String(string: String) -> ByteBuffer { + let data = Data(base64Encoded: string, options: .ignoreUnknownCharacters)! + let allocator = ByteBufferAllocator() + var buffer = allocator.buffer(capacity: data.count) + buffer.write(data: data) + return buffer + } + + /// Drip-feeds the client hello in one byte at a time. + /// Also asserts that the channel handler does not remove itself from + /// the pipeline or emit its buffered data until the future fires. + func dripFeedHello(clientHello: String, expectedResult: SniResult) throws { + var called = false + var buffer = bufferForBase64String(string: clientHello) + let channel = EmbeddedChannel() + let loop = channel.eventLoop as! EmbeddedEventLoop + let continuePromise: Promise = loop.newPromise() + + let handler = SniHandler { result in + XCTAssertEqual(expectedResult, result) + called = true + return continuePromise.futureResult + } + + try channel.pipeline.add(handler: handler).wait() + + // The handler will run when the last byte of the extension data is sent. + // We don't know when that is, so don't try to predict it. However, + // for this entire time the handler should remain in the pipeline and not + // forward on any data. + while buffer.readableBytes > 0 { + let writeableData = buffer.readSlice(length: 1)! + try channel.writeInbound(data: writeableData) + try loop.run() + + XCTAssertNil(channel.readInbound()) + try channel.pipeline.assertContains(handler: handler) + } + + // The callback should now have fired, but the handler should still not have + // sent on any data and should still be in the pipeline. + XCTAssertTrue(called) + XCTAssertNil(channel.readInbound()) + try channel.pipeline.assertContains(handler: handler) + + // Now we're going to complete the promise and run the loop. This should cause the complete + // ClientHello to be sent on, and the SniHandler to be removed from the pipeline. + continuePromise.succeed(result: ()) + try loop.run() + + let writtenBuffer: ByteBuffer = channel.readInbound()! + let writtenData = writtenBuffer.data(at: writtenBuffer.readerIndex, length: writtenBuffer.readableBytes) + let expectedData = Data(base64Encoded: clientHello, options: .ignoreUnknownCharacters)! + XCTAssertEqual(writtenData, expectedData) + + try channel.pipeline.assertDoesNotContain(handler: handler) + } + + /// Blasts the client hello in as a single string. This is not expected to reveal bugs + /// that the drip feed doesn't hit: it just helps to find more gross logic bugs. + func blastHello(clientHello: String, expectedResult: SniResult) throws { + var called = false + let buffer = bufferForBase64String(string: clientHello) + let channel = EmbeddedChannel() + let loop = channel.eventLoop as! EmbeddedEventLoop + let continuePromise: Promise = loop.newPromise() + + let handler = SniHandler { result in + XCTAssertEqual(expectedResult, result) + called = true + return continuePromise.futureResult + } + + try channel.pipeline.add(handler: handler).wait() + + // Ok, let's go. + try channel.writeInbound(data: buffer) + try loop.run() + + // The callback should have fired, but the handler should not have + // sent on any data and should still be in the pipeline. + XCTAssertTrue(called) + XCTAssertNil(channel.readInbound()) + try channel.pipeline.assertContains(handler: handler) + + // Now we're going to complete the promise and run the loop. This should cause the complete + // ClientHello to be sent on, and the SniHandler to be removed from the pipeline. + continuePromise.succeed(result: ()) + try loop.run() + + let writtenBuffer: ByteBuffer = channel.readInbound()! + let writtenData = writtenBuffer.data(at: writtenBuffer.readerIndex, length: writtenBuffer.readableBytes) + let expectedData = Data(base64Encoded: clientHello, options: .ignoreUnknownCharacters)! + XCTAssertEqual(writtenData, expectedData) + + try channel.pipeline.assertDoesNotContain(handler: handler) + } + + func testLibre227NoSniDripFeed() throws { + try dripFeedHello(clientHello: libressl227HelloNoSni, expectedResult: .fallback) + } + + func testLibre227WithSniDripFeed() throws { + try dripFeedHello(clientHello: libressl227HelloWithSni, expectedResult: .hostname("httpbin.org")) + } + + func testOpenSSL102NoSniDripFeed() throws { + try dripFeedHello(clientHello: openssl102HelloNoSni, expectedResult: .fallback) + } + + func testOpenSSL102WithSniDripFeed() throws { + try dripFeedHello(clientHello: openssl102HelloWithSni, expectedResult: .hostname("httpbin.org")) + } + + func testCurlSecureTransportDripFeed() throws { + try dripFeedHello(clientHello: curlWithSecureTransport, expectedResult: .hostname("httpbin.org")) + } + + func testSafariDripFeed() throws { + try dripFeedHello(clientHello: safariWithSecureTransport, expectedResult: .hostname("httpbin.org")) + } + + func testChromeDripFeed() throws { + try dripFeedHello(clientHello: chromeWithBoringSSL, expectedResult: .hostname("httpbin.org")) + } + + func testFirefoxDripFeed() throws { + try dripFeedHello(clientHello: firefoxWithNSS, expectedResult: .hostname("httpbin.org")) + } + + func testLibre227NoSniBlast() throws { + try blastHello(clientHello: libressl227HelloNoSni, expectedResult: .fallback) + } + + func testLibre227WithSniBlast() throws { + try blastHello(clientHello: libressl227HelloWithSni, expectedResult: .hostname("httpbin.org")) + } + + func testOpenSSL102NoSniBlast() throws { + try blastHello(clientHello: openssl102HelloNoSni, expectedResult: .fallback) + } + + func testOpenSSL102WithSniBlast() throws { + try blastHello(clientHello: openssl102HelloWithSni, expectedResult: .hostname("httpbin.org")) + } + + func testCurlSecureTransportBlast() throws { + try blastHello(clientHello: curlWithSecureTransport, expectedResult: .hostname("httpbin.org")) + } + + func testSafariBlast() throws { + try blastHello(clientHello: safariWithSecureTransport, expectedResult: .hostname("httpbin.org")) + } + + func testChromeBlast() throws { + try blastHello(clientHello: chromeWithBoringSSL, expectedResult: .hostname("httpbin.org")) + } + + func testFirefoxBlast() throws { + try blastHello(clientHello: firefoxWithNSS, expectedResult: .hostname("httpbin.org")) + } + + func testIgnoresUnknownRecordTypes() throws { + try blastHello(clientHello: alertFatalInternalError, expectedResult: .fallback) + } + + func testIgnoresUnknownTlsVersions() throws { + try blastHello(clientHello: invalidTlsVersion, expectedResult: .fallback) + } + + func testIgnoresNonClientHelloHandshakeMessages() throws { + try blastHello(clientHello: clientKeyExchange, expectedResult: .fallback) + } + + func testIgnoresInvalidHandshakeLength() throws { + try blastHello(clientHello: invalidHandshakeLength, expectedResult: .fallback) + } + + func testIgnoresInvalidCipherSuiteLength() throws { + try blastHello(clientHello: invalidCipherSuitesLength, expectedResult: .fallback) + } + + func testIgnoresInvalidCompressionLength() throws { + try blastHello(clientHello: invalidCompressionLength, expectedResult: .fallback) + } + + func testIgnoresInvalidExtensionLength() throws { + try blastHello(clientHello: invalidExtensionLength, expectedResult: .fallback) + } + + func testIgnoresInvalidIndividualExtensionLength() throws { + try blastHello(clientHello: invalidIndividualExtensionLength, expectedResult: .fallback) + } + + func testIgnoresUnknownNameType() throws { + try blastHello(clientHello: unknownNameType, expectedResult: .fallback) + } + + func testIgnoresInvalidNameLength() throws { + try blastHello(clientHello: invalidNameLength, expectedResult: .fallback) + } + + func testIgnoresInvalidNameExtensionLength() throws { + try blastHello(clientHello: invalidNameExtensionLength, expectedResult: .fallback) + } + + func testQuiteTruncatedPacket() throws { + try blastHello(clientHello: quiteTruncatedPacket, expectedResult: .fallback) + } + + func testLudicrouslyTruncatedPacket() throws { + try blastHello(clientHello: ludicrouslyTruncatedPacket, expectedResult: .fallback) + } +}