Enable TLS certificate validation on Apple platforms. (#72)

Motivation:

While our main use-case is users on Linux, many of our users develop on
their Mac. We need to support their development model, which may well
involve making outbound requests. Those requests need certificate
validation.

Modifications:

- Added routines for using Security.framework to validate cert chains.
- Refactored code to be as platform-independent as possible.

Result:

Certificate verification works on Apple platforms.
This commit is contained in:
Cory Benfield authored and Johannes Weiss committed 2019-03-13 14:59:04 +00:00
1 parent 3ae0a3b6e0
commit 7eeb331c02
9 files changed
+307 -34

No files matched your search

+11 -5
View File
@@ -268,15 +268,21 @@ final class ByteBufferBIO {
/// Stores a buffer received from the network for delivery to BoringSSL.
///
/// Whenever a buffer is received from the network, it is passed to the BIO via this function
/// call. Only one buffer may be passed to BoringSSL at any one time: once a buffer is passed, it
/// is expected to be cleared immediately. If it is not cleared, this is an application error and
/// must be resolved.
/// call. In almost all cases this BIO should be immediately consumed by BoringSSL, but in some cases
/// it may not be. In those cases, additional calls will cause byte-by-byte copies. This should
/// be avoided, but usually only happens during asynchronous certificate verification in the
/// handshake.
///
/// - parameters:
/// - buffer: The buffer of ciphertext bytes received from the network.
func receiveFromNetwork(buffer: ByteBuffer) {
precondition(self.inboundBuffer == nil, "Did not flush inbound bytes to BoringSSL")
self.inboundBuffer = buffer
var buffer = buffer
if self.inboundBuffer == nil {
self.inboundBuffer = buffer
} else {
self.inboundBuffer!.writeBuffer(&buffer)
}
}
/// Retrieves any inbound data that has not been processed by BoringSSL.
+2 -2
View File
@@ -43,13 +43,13 @@ public final class NIOSSLClientHandler: NIOSSLHandler {
}
// IP addresses must not be provided in the SNI extension, so filter them.
try connection.setSNIServerName(name: serverHostname)
try connection.setServerName(name: serverHostname)
}
if let verificationCallback = verificationCallback {
connection.setVerificationCallback(verificationCallback)
}
super.init(connection: connection, expectedHostname: serverHostname)
super.init(connection: connection)
}
}
+18 -13
View File
@@ -48,17 +48,18 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo
private var shutdownPromise: EventLoopPromise<Void>?
private var didDeliverData: Bool = false
private var storedContext: ChannelHandlerContext? = nil
private let expectedHostname: String?
internal init (connection: SSLConnection, expectedHostname: String? = nil) {
internal init (connection: SSLConnection) {
self.connection = connection
self.bufferedWrites = MarkedCircularBuffer(initialCapacity: 96) // 96 brings the total size of the buffer to just shy of one page
self.expectedHostname = expectedHostname
}
public func handlerAdded(context: ChannelHandlerContext) {
self.storedContext = context
self.connection.setAllocator(context.channel.allocator)
self.connection.parentHandler = self
self.connection.eventLoop = context.eventLoop
self.plaintextReadBuffer = context.channel.allocator.buffer(capacity: SSL_MAX_RECORD_SIZE)
// If this channel is already active, immediately begin handshaking.
if context.channel.isActive {
@@ -468,16 +469,7 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo
throw NIOSSLError.cannotFindPeerIP
}
// We want the leaf certificate.
guard let peerCert = connection.getPeerCertificate() else {
throw NIOSSLError.noCertificateToValidate
}
guard try validIdentityForService(serverHostname: expectedHostname,
socketAddress: ipAddress,
leafCertificate: peerCert) else {
throw NIOSSLError.unableToValidateCertificate
}
try connection.validateHostname(address: ipAddress)
}
}
@@ -631,3 +623,16 @@ fileprivate extension MarkedCircularBuffer {
}
}
}
// MARK:- Code for handling asynchronous handshake resumption.
extension NIOSSLHandler {
internal func asynchronousCertificateVerificationComplete() {
guard let storedContext = self.storedContext else {
// Oh well, the connection is dead. Do nothing.
return
}
self.doHandshakeStep(context: storedContext)
}
}
+124 -6
View File
@@ -20,7 +20,7 @@ internal let SSL_MAX_RECORD_SIZE = 16 * 1024
/// This is used as the application data index to store pointers to `SSLConnection` objects in
/// `SSL` objects. It is only safe to use after BoringSSL initialization. As it's declared global,
/// it will be lazily initialized and protected by a dispatch_once, ensuring that it's thread-safe.
private let exDataIndex = CNIOBoringSSL_SSL_get_ex_new_index(0, nil, nil, nil, nil)
internal let sslConnectionExDataIndex = CNIOBoringSSL_SSL_get_ex_new_index(0, nil, nil, nil, nil)
/// Encodes the return value of a non-blocking BoringSSL method call.
///
@@ -45,6 +45,11 @@ internal final class SSLConnection {
private let parentContext: NIOSSLContext
private var bio: ByteBufferBIO?
private var verificationCallback: NIOSSLVerificationCallback?
internal var platformVerificationState: PlatformVerificationState = PlatformVerificationState()
internal var expectedHostname: String?
internal var role: ConnectionRole?
internal var parentHandler: NIOSSLHandler?
internal var eventLoop: EventLoop?
/// Whether certificate hostnames should be validated.
var validateHostnames: Bool {
@@ -60,7 +65,7 @@ internal final class SSLConnection {
// We pass the SSL object an unowned reference to this object.
let pointerToSelf = Unmanaged.passUnretained(self).toOpaque()
CNIOBoringSSL_SSL_set_ex_data(self.ssl, exDataIndex, pointerToSelf)
CNIOBoringSSL_SSL_set_ex_data(self.ssl, sslConnectionExDataIndex, pointerToSelf)
}
deinit {
@@ -70,11 +75,13 @@ internal final class SSLConnection {
/// Configures this as a server connection.
func setAcceptState() {
CNIOBoringSSL_SSL_set_accept_state(ssl)
self.role = .server
}
/// Configures this as a client connection.
func setConnectState() {
CNIOBoringSSL_SSL_set_connect_state(ssl)
self.role = .client
}
func setAllocator(_ allocator: ByteBufferAllocator) {
@@ -92,7 +99,7 @@ internal final class SSLConnection {
/// This method must only be called with a hostname, not an IP address. Sending
/// an IP address in the SNI extension is invalid, and may result in handshake
/// failure.
func setSNIServerName(name: String) throws {
func setServerName(name: String) throws {
CNIOBoringSSL_ERR_clear_error()
let rc = name.withCString {
return CNIOBoringSSL_SSL_set_tlsext_host_name(ssl, $0)
@@ -100,6 +107,7 @@ internal final class SSLConnection {
guard rc == 1 else {
throw BoringSSLError.invalidSNIName(BoringSSLError.buildErrorStack())
}
self.expectedHostname = name
}
/// Sets the BoringSSL verification callback.
@@ -126,9 +134,9 @@ internal final class SSLConnection {
guard let ssl = CNIOBoringSSL_X509_STORE_CTX_get_ex_data(storeContext, CNIOBoringSSL_SSL_get_ex_data_X509_STORE_CTX_idx()) else {
preconditionFailure("Unable to obtain SSL * from X509_STORE_CTX * \(String(describing: storeContext))")
}
guard let connectionPointer = CNIOBoringSSL_SSL_get_ex_data(OpaquePointer(ssl), exDataIndex) else {
guard let connectionPointer = CNIOBoringSSL_SSL_get_ex_data(OpaquePointer(ssl), sslConnectionExDataIndex) else {
// Uh-ok, our application state is gone. Don't let this error silently pass, go bang.
preconditionFailure("Unable to find application data from SSL * \(ssl), index \(exDataIndex)")
preconditionFailure("Unable to find application data from SSL * \(ssl), index \(sslConnectionExDataIndex)")
}
// Grab a connection
@@ -142,6 +150,20 @@ internal final class SSLConnection {
}
}
/// Performs hostname validation against the peer certificate using the configured server name.
func validateHostname(address: SocketAddress) throws {
// We want the leaf certificate.
guard let peerCert = self.getPeerCertificate() else {
throw NIOSSLError.noCertificateToValidate
}
guard try validIdentityForService(serverHostname: self.expectedHostname,
socketAddress: address,
leafCertificate: peerCert) else {
throw NIOSSLError.unableToValidateCertificate
}
}
/// Spins the handshake state machine and performs the next step of the handshake
/// protocol.
///
@@ -160,7 +182,8 @@ internal final class SSLConnection {
switch error {
case .wantRead,
.wantWrite:
.wantWrite,
.wantCertificateVerify:
return .incomplete
default:
return .failed(error)
@@ -320,6 +343,9 @@ internal final class SSLConnection {
/// Drop the verification callback. This breaks any reference cycles that are inevitably
/// created by this callback.
self.verificationCallback = nil
// Also drop the reference to the parent channel handler, which is a trivial reference cycle.
self.parentHandler = nil
}
/// Retrieves any inbound data that has not been processed by BoringSSL.
@@ -336,3 +362,95 @@ internal final class SSLConnection {
return self.bio?.evacuateInboundData()
}
}
/// MARK: ConnectionRole
extension SSLConnection {
internal enum ConnectionRole {
case server
case client
}
}
// MARK: Certificate Peer Chain Buffers
extension SSLConnection {
/// A collection of buffers representing the DER-encoded bytes of the peer certificate chain.
struct PeerCertificateChainBuffers {
private let basePointer: OpaquePointer
fileprivate init(basePointer: OpaquePointer) {
self.basePointer = basePointer
}
}
/// Invokes a block with a collection of pointers to DER-encoded bytes of the peer certificate chain.
///
/// The pointers are only guaranteed to be valid for the duration of this call: it is undefined behaviour to escape
/// any of these pointers from the block, or the certificate iterator itself from the block. Users must either use the
/// bytes synchronously within the block, or they must copy them to a new buffer that they own.
///
/// If there are no peer certificates, the body will be called with nil.
func withPeerCertificateChainBuffers<Result>(_ body: (PeerCertificateChainBuffers?) throws -> Result) rethrows -> Result {
guard let stackPointer = CNIOBoringSSL_SSL_get0_peer_certificates(self.ssl) else {
return try body(nil)
}
return try body(PeerCertificateChainBuffers(basePointer: stackPointer))
}
}
extension SSLConnection.PeerCertificateChainBuffers: RandomAccessCollection {
struct Index: Hashable, Comparable, Strideable {
typealias Stride = Int
fileprivate var index: Int
fileprivate init(_ index: Int) {
self.index = index
}
static func < (lhs: Index, rhs: Index) -> Bool {
return lhs.index < rhs.index
}
func advanced(by n: SSLConnection.PeerCertificateChainBuffers.Index.Stride) -> SSLConnection.PeerCertificateChainBuffers.Index {
var result = self
result.index += n
return result
}
func distance(to other: SSLConnection.PeerCertificateChainBuffers.Index) -> SSLConnection.PeerCertificateChainBuffers.Index.Stride {
return other.index - self.index
}
}
typealias Element = UnsafeRawBufferPointer
var startIndex: Index {
return Index(0)
}
var endIndex: Index {
return Index(self.count)
}
var count: Int {
return CNIOBoringSSL_sk_CRYPTO_BUFFER_num(self.basePointer)
}
subscript(_ index: Index) -> UnsafeRawBufferPointer {
precondition(index < self.endIndex)
guard let ptr = CNIOBoringSSL_sk_CRYPTO_BUFFER_value(self.basePointer, index.index) else {
preconditionFailure("Unable to locate backing pointer.")
}
guard let dataPointer = CNIOBoringSSL_CRYPTO_BUFFER_data(ptr) else {
preconditionFailure("Unable to retrieve data pointer from crypto_buffer")
}
let byteCount = CNIOBoringSSL_CRYPTO_BUFFER_len(ptr)
// We want an UnsafeRawBufferPointer here, so we need to erase the pointer type.
let bufferDataPointer = UnsafeBufferPointer(start: dataPointer, count: byteCount)
return UnsafeRawBufferPointer(bufferDataPointer)
}
}
+4 -3
View File
@@ -382,9 +382,8 @@ extension NIOSSLContext {
}
private static func platformDefaultConfiguration(context: OpaquePointer) throws {
// Platform default trust is configured differently in different places. On Darwin we currently do
// nothing (watch this space). On Linux, we use our searched heuristics to guess about where the platform
// trust store is.
// Platform default trust is configured differently in different places. On Darwin we invoke Security.framework in a custom callback.
// On Linux, we use our searched heuristics to guess about where the platform trust store is.
#if os(Linux)
let result = rootCAFilePath.withCString { rootCAFilePointer in
rootCADirectoryPath.withCString { rootCADirectoryPointer in
@@ -396,6 +395,8 @@ extension NIOSSLContext {
let errorStack = BoringSSLError.buildErrorStack()
throw BoringSSLError.unknownError(errorStack)
}
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
CNIOBoringSSL_SSL_CTX_set_custom_verify(context, SSL_VERIFY_PEER, securityFrameworkCustomVerify)
#endif
}
}
+4
View File
@@ -91,6 +91,7 @@ public enum BoringSSLError: Error {
case wantConnect
case wantAccept
case wantX509Lookup
case wantCertificateVerify
case syscallError
case sslError(NIOBoringSSLErrorStack)
case unknownError(NIOBoringSSLErrorStack)
@@ -108,6 +109,7 @@ public func ==(lhs: BoringSSLError, rhs: BoringSSLError) -> Bool {
(.wantWrite, .wantWrite),
(.wantConnect, .wantConnect),
(.wantAccept, .wantAccept),
(.wantCertificateVerify, .wantCertificateVerify),
(.wantX509Lookup, .wantX509Lookup),
(.syscallError, .syscallError):
return true
@@ -134,6 +136,8 @@ internal extension BoringSSLError {
return .wantConnect
case SSL_ERROR_WANT_ACCEPT:
return .wantAccept
case SSL_ERROR_WANT_CERTIFICATE_VERIFY:
return .wantCertificateVerify
case SSL_ERROR_WANT_X509_LOOKUP:
return .wantX509Lookup
case SSL_ERROR_SYSCALL:
@@ -0,0 +1,139 @@
//===----------------------------------------------------------------------===//
//
// 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 CNIOBoringSSL
/// The current state of the platform verification helper, if one is in use.
///
/// Only used on Apple platforms currently.
internal struct PlatformVerificationState {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
fileprivate var state: SecurityFrameworkVerificationState? = nil
#endif
}
// We can only use Security.framework to validate TLS certificates on Apple platforms.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Dispatch
import Foundation
import Security
/// A custom certificate verification function for BoringSSL that uses Security.framework to provide certificate verification.
///
/// - parameters:
/// - ssl: The pointer to the SSL * object for this connection.
/// - outAlert: A C-style inout parameter that contains a pointer to an alert. Is assumed to be non-null.
internal func securityFrameworkCustomVerify(_ ssl: OpaquePointer?, _ outAlert: UnsafeMutablePointer<UInt8>?) -> ssl_verify_result_t {
guard let unwrappedSSL = ssl, let unwrappedOutAlert = outAlert else {
preconditionFailure("Unexpected null pointer in custom verification callback. ssl: \(String(describing: ssl)) outAlert: \(String(describing: outAlert))")
}
// Ok, this call may be a resumption of a previous negotiation. We need to check if our connection object has a pre-existing verifiation state.
guard let connectionPointer = CNIOBoringSSL_SSL_get_ex_data(unwrappedSSL, sslConnectionExDataIndex) else {
// Uh-ok, our application state is gone. Don't let this error silently pass, go bang.
preconditionFailure("Unable to find application data from SSL * \(unwrappedSSL), index \(sslConnectionExDataIndex)")
}
let connection = Unmanaged<SSLConnection>.fromOpaque(connectionPointer).takeUnretainedValue()
do {
return try connection.performSecurityFrameworkValidation()
} catch {
unwrappedOutAlert.pointee = UInt8(SSL_AD_INTERNAL_ERROR)
return ssl_verify_invalid
}
}
extension PlatformVerificationState {
fileprivate enum SecurityFrameworkVerificationState {
case pendingResult
case complete(SecTrustResultType)
}
}
extension SSLConnection {
func performSecurityFrameworkValidation() throws -> ssl_verify_result_t {
// First, check whether we have an outstanding or completed query. If we do, don't do any other work.
switch self.platformVerificationState.state {
case .some(.complete(.proceed)), .some(.complete(.unspecified)):
// These two cases mean we have successfully validated the certificate. We're done! Wipe out the state so
// that if we need to reverify we can, and return the success.
self.platformVerificationState.state = nil
return ssl_verify_ok
case .some(.complete):
// Ok, this broader case means we failed. We're still done, but return the failure instead.
self.platformVerificationState.state = nil
return ssl_verify_invalid
case .some(.pendingResult):
// We've got a validation attempt outstanding. Tell BoringSSL to hold its horses.
return ssl_verify_retry
case .none:
// No verification outstanding: do more work.
break
}
// Ok, time to kick off a validation. Let's get some certificate buffers.
let certificates: [SecCertificate] = try self.withPeerCertificateChainBuffers { buffers in
guard let buffers = buffers else {
throw NIOSSLError.unableToValidateCertificate
}
return try buffers.map { buffer in
let data = Data(bytes: buffer.baseAddress!, count: buffer.count)
guard let cert = SecCertificateCreateWithData(nil, data as CFData) else {
throw NIOSSLError.unableToValidateCertificate
}
return cert
}
}
// This force-unwrap is safe as we must have decided if we're a client or a server before validation.
var trust: SecTrust? = nil
var result: OSStatus
let policy = SecPolicyCreateSSL(self.role! == .server, self.expectedHostname as CFString?)
result = SecTrustCreateWithCertificates(certificates as CFArray, policy, &trust)
guard result == errSecSuccess, let actualTrust = trust else {
throw NIOSSLError.unableToValidateCertificate
}
// We create a DispatchQueue here to be called back on, as this validation may perform network activity.
let callbackQueue = DispatchQueue(label: "io.swiftnio.ssl.validationCallbackQueue")
// Now we need to grab some things we need in the callback block. Specifically, we need the parent handler
// and the event loop it belongs to. This is because we cannot safely access these things from inside the
// block, and we need the eventLoop to get back onto a safe thread.
//
// We don't hold these references weak because we are ok with keeping the handler alive longer than necessary
// in the rare case that the handler is removed before the callback completes.
// The force-unwrap is safe, as we cannot be midway through handshaking before the connection has become active.
let eventLoop = self.eventLoop!
result = SecTrustEvaluateAsync(actualTrust, callbackQueue) { (_, result) in
// When we complete here we need to set our result state, and then ask to respin certificate verification.
// If we can't respin verification because we've dropped the parent handler, that's fine, no harm no foul.
eventLoop.execute {
self.platformVerificationState.state = .complete(result)
self.parentHandler?.asynchronousCertificateVerificationComplete()
}
}
guard result == errSecSuccess else {
throw NIOSSLError.unableToValidateCertificate
}
return ssl_verify_retry
}
}
#endif
+1 -1
View File
@@ -301,7 +301,7 @@ func addExtension(x509: UnsafeMutablePointer<X509>, nid: Int32, value: String) {
func generateSelfSignedCert() -> (NIOSSLCertificate, NIOSSLPrivateKey) {
let pkey = generateRSAPrivateKey()
let x = CNIOBoringSSL_X509_new()!
CNIOBoringSSL_X509_set_version(x, 3)
CNIOBoringSSL_X509_set_version(x, 2)
// NB: X509_set_serialNumber uses an internal copy of the ASN1_INTEGER, so this is
// safe, there will be no use-after-free.
+4 -4
View File
@@ -110,7 +110,7 @@ class TLSConfigurationTest: XCTestCase {
func assertPostHandshakeError(withClientConfig clientConfig: TLSConfiguration,
andServerConfig serverConfig: TLSConfiguration,
errorTextContains message: String,
errorTextContainsAnyOf messages: [String],
file: StaticString = #file,
line: UInt = #line) throws {
let clientContext = try assertNoThrowWithValue(NIOSSLContext(configuration: clientConfig), file: file, line: line)
@@ -133,7 +133,7 @@ class TLSConfigurationTest: XCTestCase {
switch eventHandler.errors[0] {
case .sslError(let errs):
XCTAssertEqual(errs.count, 1, file: file, line: line)
let correctError = errs[0].description.contains(message)
let correctError: Bool = messages.map { errs[0].description.contains($0) }.reduce(false) { $0 || $1 }
XCTAssert(correctError, errs[0].description, file: file, line: line)
default:
XCTFail("Unexpected error: \(eventHandler.errors[0])", file: file, line: line)
@@ -187,7 +187,7 @@ class TLSConfigurationTest: XCTestCase {
maximumTLSVersion: .tlsv12,
certificateVerification: .noHostnameVerification)
try assertHandshakeError(withClientConfig: clientConfig, andServerConfig: serverConfig, errorTextContains: "ALERT_UNKNOWN_CA")
try assertHandshakeError(withClientConfig: clientConfig, andServerConfig: serverConfig, errorTextContainsAnyOf: ["ALERT_UNKNOWN_CA", "ALERT_CERTIFICATE_UNKNOWN"])
}
func testServerCannotValidateClientPostTLS13() throws {
@@ -201,7 +201,7 @@ class TLSConfigurationTest: XCTestCase {
minimumTLSVersion: .tlsv13,
certificateVerification: .noHostnameVerification)
try assertPostHandshakeError(withClientConfig: clientConfig, andServerConfig: serverConfig, errorTextContains: "ALERT_UNKNOWN_CA")
try assertPostHandshakeError(withClientConfig: clientConfig, andServerConfig: serverConfig, errorTextContainsAnyOf: ["ALERT_UNKNOWN_CA", "ALERT_CERTIFICATE_UNKNOWN"])
}
func testMutualValidation() throws {