From 8d8f7844d7a576428c78efd121a01605d947a04b Mon Sep 17 00:00:00 2001 From: Rafael Cepeda Date: Mon, 17 Aug 2026 14:48:31 +0100 Subject: [PATCH] Don't crash when a peer completes an optionalVerification handshake without a certificate (#590) ## Motivation When a `NIOSSLHandler` is created with an `additionalPeerCertificateVerificationCallback` (via `_makeSSLServerHandler` / `_makeSSLClientHandler`) and the `TLSConfiguration` uses `.optionalVerification`, the peer is allowed to complete the handshake *without* presenting a certificate. In that situation `doHandshakeStep` reached the additional-verification branch, called `connection.getPeerCertificate()`, got `nil`, and hit a `preconditionFailure`, aborting the entire process. The constructor precondition did not catch this because `.optionalVerification` is `.none(validatePresentedCertificates: true)`, which is distinct from `.none` and therefore passes the `!= .none` check. ## Modifications - In `NIOSSLHandler.doHandshakeStep`, only invoke the `additionalPeerCertificateVerificationCallback` when the peer actually presented a certificate. The callback binding and the `getPeerCertificate()` binding are now combined into a single `if let ..., let ...`; if no certificate was presented the handshake completes normally without invoking the callback. This preserves the previous behaviour of only calling `getPeerCertificate()` when a callback is set (short-circuit ordering). - Removed the now-unreachable `preconditionFailure`. - Added an integration test that stands up a server with `.optionalVerification` and an `additionalPeerCertificateVerificationCallback`, connects a client that presents no certificate, and asserts the connection is handled without crashing the process. ## Result A peer that completes an `.optionalVerification` handshake without presenting a certificate no longer crashes the process. The additional verification callback still runs, unchanged, whenever a certificate *is* presented, so behaviour for the certificate-present path is unaffected. `.optionalVerification` + `additionalPeerCertificateVerificationCallback` is now a genuinely supported combination, matching what the constructor precondition already advertised. --------- Co-authored-by: Aryan Shah --- .gitignore | 2 + Sources/NIOSSL/NIOSSLHandler.swift | 39 +++-- Sources/NIOSSL/TLSConfiguration.swift | 15 ++ Tests/NIOSSLTests/NIOSSLIntegrationTest.swift | 133 ++++++++++++++++++ 4 files changed, 174 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index 3961b9db..107d271b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .DS_Store /.build +*/.build /Packages /*.xcodeproj Package.pins @@ -9,3 +10,4 @@ Package.resolved DerivedData /.idea .swiftpm +.vscode diff --git a/Sources/NIOSSL/NIOSSLHandler.swift b/Sources/NIOSSL/NIOSSLHandler.swift index 33d9c3d9..798b853c 100644 --- a/Sources/NIOSSL/NIOSSLHandler.swift +++ b/Sources/NIOSSL/NIOSSLHandler.swift @@ -376,23 +376,32 @@ public class NIOSSLHandler: ChannelInboundHandler, ChannelOutboundHandler, Remov } if let additionalPeerCertificateVerificationCallback = self.additionalPeerCertificateVerificationCallback { - state = .additionalVerification - guard let peerCertificate = connection.getPeerCertificate() else { - preconditionFailure( - """ - Couldn't get peer certificate after chain verification was successful. - This should be impossible as we have a precondition during creation of this handler that requires certificate verification. - Please file an issue. - """ + if let peerCertificate = connection.getPeerCertificate() { + state = .additionalVerification + additionalPeerCertificateVerificationCallback(peerCertificate, context.channel) + .hop(to: context.eventLoop) + .assumeIsolated() + .whenComplete { result in + self.completedAdditionalPeerCertificateVerification(result: result) + } + return + } else if self.connection.parentContext.configuration.certificateVerification.requiresPeerCertificate { + // The peer presented no certificate even though verification required one. + // BoringSSL sets `SSL_VERIFY_FAIL_IF_NO_PEER_CERT` for these modes, so it + // should have failed the handshake before reaching `.complete`; this branch + // should be unreachable. If it ever is reached we must fail closed rather + // than accept an unauthenticated peer or silently skip the callback. + assertionFailure( + "Reached handshake completion with no peer certificate despite required certificate verification." ) + let error = NIOSSLError.noCertificateToValidate + context.fireErrorCaught(error) + channelClose(context: context, reason: error) + return } - additionalPeerCertificateVerificationCallback(peerCertificate, context.channel) - .hop(to: context.eventLoop) - .assumeIsolated() - .whenComplete { result in - self.completedAdditionalPeerCertificateVerification(result: result) - } - return + // Otherwise verification is optional and the peer presented no certificate: there + // is nothing to verify, so we skip the callback and accept the connection, + // consistent with `.optionalVerification`'s semantics. } state = .active diff --git a/Sources/NIOSSL/TLSConfiguration.swift b/Sources/NIOSSL/TLSConfiguration.swift index 6f52486f..2893a48c 100644 --- a/Sources/NIOSSL/TLSConfiguration.swift +++ b/Sources/NIOSSL/TLSConfiguration.swift @@ -212,6 +212,21 @@ extension CertificateVerification: Hashable { // empty } +extension CertificateVerification { + /// Whether this mode requires the peer to present a certificate. + /// + /// This must stay in sync with the BoringSSL verification setup in `NIOSSLContext`: only the + /// modes that map to `SSL_VERIFY_FAIL_IF_NO_PEER_CERT` require a certificate. + internal var requiresPeerCertificate: Bool { + switch self { + case .fullVerification, .noHostnameVerification: + return true + case .none: + return false + } + } +} + /// Support for TLS renegotiation. /// /// In general, renegotiation should not be enabled except in circumstances where it is absolutely necessary. diff --git a/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift b/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift index 5bdb4a63..f4c57e95 100644 --- a/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift +++ b/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift @@ -1521,6 +1521,139 @@ class NIOSSLIntegrationTest: XCTestCase { XCTAssertTrue(actualErrors.first is CustomUserError) } + func testOptionalVerificationWithAdditionalCallbackAndNoClientCertificateDoesNotCrash() throws { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + defer { + XCTAssertNoThrow(try group.syncShutdownGracefully()) + } + + // Server: `.optionalVerification` (requests but does not require a client cert) plus + // an additional peer-certificate verification callback. + var serverConfig = TLSConfiguration.makeServerConfiguration( + certificateChain: [.certificate(NIOSSLIntegrationTest.cert)], + privateKey: .privateKey(NIOSSLIntegrationTest.key) + ) + serverConfig.certificateVerification = .optionalVerification + serverConfig.trustRoots = .certificates([NIOSSLIntegrationTest.cert]) + let serverCtx = try assertNoThrowWithValue(NIOSSLContext(configuration: serverConfig)) + + // Client presents no certificate of its own. + let clientCtx = try configuredClientContext() + + let serverChannel = try assertNoThrowWithValue( + ServerBootstrap(group: group) + .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) + .childChannelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + let handler = NIOSSLServerHandler._makeSSLServerHandler( + context: serverCtx, + additionalPeerCertificateVerificationCallback: { _, channel in + channel.eventLoop.makeSucceededFuture(()) + } + ) + try channel.pipeline.syncOperations.addHandler(handler) + } + } + .bind(host: "127.0.0.1", port: 0).wait() + ) + defer { + XCTAssertNoThrow(try serverChannel.close().wait()) + } + + let eventHandler = EventRecorderHandler() + let clientChannel = try clientTLSChannel( + context: clientCtx, + preHandlers: [], + postHandlers: [eventHandler], + group: group, + connectingTo: serverChannel.localAddress!, + serverHostname: "localhost" + ) + defer { + XCTAssertNoThrow(try? clientChannel.close().wait()) + } + + var originalBuffer = clientChannel.allocator.buffer(capacity: 5) + originalBuffer.writeString("Hello") + let writeFuture = clientChannel.writeAndFlush(originalBuffer) + writeFuture.whenComplete { _ in + XCTAssertEqual( + eventHandler.events[..<3], + [.Registered, .Active, .UserEvent(.handshakeCompleted(negotiatedProtocol: nil))] + ) + } + try writeFuture.wait() + } + + // A server that *requires* a client certificate (`.fullVerification`) and has an additional + // peer certificate verification callback must reject a client that presents no certificate, + // and must never invoke the callback for such a connection. BoringSSL enforces this with + // `SSL_VERIFY_FAIL_IF_NO_PEER_CERT` before the handshake completes; this test guards against a + // regression that would fail open (accept the connection and/or skip the callback) instead. + func testFullVerificationWithAdditionalCallbackRejectsClientWithNoCertificate() throws { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + defer { + XCTAssertNoThrow(try group.syncShutdownGracefully()) + } + + // Server: `.fullVerification` (requires a client cert) plus an additional + // peer-certificate verification callback. + var serverConfig = TLSConfiguration.makeServerConfiguration( + certificateChain: [.certificate(NIOSSLIntegrationTest.cert)], + privateKey: .privateKey(NIOSSLIntegrationTest.key) + ) + serverConfig.certificateVerification = .fullVerification + serverConfig.trustRoots = .certificates([NIOSSLIntegrationTest.cert]) + let serverCtx = try assertNoThrowWithValue(NIOSSLContext(configuration: serverConfig)) + + // Client presents no certificate of its own. + let clientCtx = try configuredClientContext() + + let callbackInvoked = NIOLockedValueBox(false) + let errorHandler = ErrorCatcher() + + let serverChannel = try assertNoThrowWithValue( + ServerBootstrap(group: group) + .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) + .childChannelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + let handler = NIOSSLServerHandler._makeSSLServerHandler( + context: serverCtx, + additionalPeerCertificateVerificationCallback: { _, channel in + callbackInvoked.withLockedValue { $0 = true } + return channel.eventLoop.makeSucceededFuture(()) + } + ) + try channel.pipeline.syncOperations.addHandler(handler) + } + } + .bind(host: "127.0.0.1", port: 0).wait() + ) + defer { + XCTAssertNoThrow(try serverChannel.close().wait()) + } + + let clientChannel = try clientTLSChannel( + context: clientCtx, + preHandlers: [], + postHandlers: [errorHandler], + group: group, + connectingTo: serverChannel.localAddress!, + serverHostname: "localhost" + ) + defer { + XCTAssertNoThrow(try? clientChannel.close().wait()) + } + + // Wait for the connection to be torn down as a result of the failed handshake. + try clientChannel.closeFuture.wait() + + // The handshake must have failed on the client, and the server's additional verification + // callback must never run when no certificate was presented. + XCTAssertFalse(errorHandler.errors.isEmpty) + XCTAssertFalse(callbackInvoked.withLockedValue { $0 }) + } + func testFlushWhileAdditionalValidationIsInProgressDoesNotActuallyFlush() throws { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer {