Skip to content

Commit c78d228

Browse files
glbrnttMrMage
authored andcommitted
Fallback to the hostname for TLS if a hostname override isn't provided (#528)
* Fallback to the hostname for TLS if a hostname override isn't provided Motivation: TLS does not work if a hostname override was not provided and hostname verification is enabled as only the override was provided to the NIOSSLClientHandler. Modifications: Provide the SSL handler with the override, if one is provided, or the hostname otherwise. Result: Fewer TLS failures. * Log the TLS hostname * Update tests, delete unused certs/keys
1 parent d4bcd92 commit c78d228

File tree

12 files changed

+299
-260
lines changed

12 files changed

+299
-260
lines changed

Sources/GRPC/ClientConnection.swift

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,8 @@ public class ClientConnection {
142142
// Configure the channel with the correct handlers and connect to our target.
143143
let configuredChannel = ClientConnection.initializeChannel(
144144
channel,
145-
tls: configuration.tls,
145+
tls: configuration.tls?.configuration,
146+
serverHostname: configuration.tls?.hostnameOverride ?? configuration.target.host,
146147
errorDelegate: configuration.errorDelegate
147148
).flatMap {
148149
channel.connect(to: socketAddress)
@@ -325,21 +326,34 @@ extension ClientConnection {
325326
///
326327
/// - Parameter configuration: The configuration to prepare the bootstrap with.
327328
/// - Parameter group: The `EventLoopGroup` to use for the bootstrap.
328-
/// - Parameter timeout: The connection timeout in seconds.
329+
/// - Parameter timeout: The connection timeout in seconds.
329330
private class func makeBootstrap(
330331
configuration: Configuration,
331332
group: EventLoopGroup,
332333
timeout: TimeInterval?,
333334
logger: Logger
334335
) -> ClientBootstrapProtocol {
336+
// Provide a server hostname if we're using TLS. Prefer the override.
337+
let serverHostname: String? = configuration.tls.map {
338+
if let hostnameOverride = $0.hostnameOverride {
339+
logger.debug("using hostname override for TLS", metadata: ["hostname-override": "\(hostnameOverride)"])
340+
return hostnameOverride
341+
} else {
342+
let host = configuration.target.host
343+
logger.debug("using host connection target for TLS", metadata: ["hostname-override": "\(host)"])
344+
return host
345+
}
346+
}
347+
335348
let bootstrap = PlatformSupport.makeClientBootstrap(group: group)
336349
// Enable SO_REUSEADDR and TCP_NODELAY.
337350
.channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
338351
.channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
339352
.channelInitializer { channel in
340353
initializeChannel(
341354
channel,
342-
tls: configuration.tls,
355+
tls: configuration.tls?.configuration,
356+
serverHostname: serverHostname,
343357
errorDelegate: configuration.errorDelegate
344358
)
345359
}
@@ -356,14 +370,16 @@ extension ClientConnection {
356370
///
357371
/// - Parameter channel: The channel to initialize.
358372
/// - Parameter tls: The optional TLS configuration for the channel.
373+
/// - Parameter serverHostname: The hostname of the server to use for TLS.
359374
/// - Parameter errorDelegate: Optional client error delegate.
360375
private class func initializeChannel(
361376
_ channel: Channel,
362-
tls: Configuration.TLS?,
377+
tls: TLSConfiguration?,
378+
serverHostname: String?,
363379
errorDelegate: ClientErrorDelegate?
364380
) -> EventLoopFuture<Void> {
365-
let tlsConfigured = tls.map { tlsConfiguration in
366-
channel.configureTLS(tlsConfiguration, errorDelegate: errorDelegate)
381+
let tlsConfigured = tls.map {
382+
channel.configureTLS($0, serverHostname: serverHostname, errorDelegate: errorDelegate)
367383
}
368384

369385
return (tlsConfigured ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
@@ -484,15 +500,18 @@ fileprivate extension Channel {
484500
/// the `TLSVerificationHandler` which verifies that a successful handshake was completed.
485501
///
486502
/// - Parameter configuration: The configuration to configure the channel with.
503+
/// - Parameter serverHostname: The server hostname to use if the hostname should be verified.
487504
/// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
488505
func configureTLS(
489-
_ configuration: ClientConnection.Configuration.TLS,
506+
_ configuration: TLSConfiguration,
507+
serverHostname: String?,
490508
errorDelegate: ClientErrorDelegate?
491509
) -> EventLoopFuture<Void> {
492510
do {
493511
let sslClientHandler = try NIOSSLClientHandler(
494-
context: try NIOSSLContext(configuration: configuration.configuration),
495-
serverHostname: configuration.hostnameOverride)
512+
context: try NIOSSLContext(configuration: configuration),
513+
serverHostname: serverHostname
514+
)
496515

497516
return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler())
498517
} catch {

Sources/GRPCSampleData/GRPCSwiftCertificate.swift

Lines changed: 156 additions & 98 deletions
Large diffs are not rendered by default.

Tests/GRPCTests/BasicEchoTestCase.swift

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,16 +78,14 @@ extension TransportSecurity {
7878
return nil
7979

8080
case .anonymousClient:
81-
return .init(
82-
trustRoots: .certificates([self.caCert]),
83-
certificateVerification: .noHostnameVerification)
81+
return .init(trustRoots: .certificates([self.caCert]))
8482

8583
case .mutualAuthentication:
8684
return .init(
8785
certificateChain: [.certificate(self.clientCert)],
8886
privateKey: .privateKey(SamplePrivateKey.client),
89-
trustRoots: .certificates([self.caCert]),
90-
certificateVerification: .noHostnameVerification)
87+
trustRoots: .certificates([self.caCert])
88+
)
9189
}
9290
}
9391
}
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import Foundation
2+
import GRPC
3+
import GRPCSampleData
4+
import NIO
5+
import NIOSSL
6+
import XCTest
7+
8+
class ClientTLSHostnameOverrideTests: GRPCTestCase {
9+
var eventLoopGroup: EventLoopGroup!
10+
var server: Server!
11+
var connection: ClientConnection!
12+
13+
override func setUp() {
14+
super.setUp()
15+
self.eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
16+
}
17+
18+
override func tearDown() {
19+
super.tearDown()
20+
XCTAssertNoThrow(try self.server.close().wait())
21+
XCTAssertNoThrow(try connection.close().wait())
22+
XCTAssertNoThrow(try self.eventLoopGroup.syncShutdownGracefully())
23+
}
24+
25+
func makeEchoServer(tls: Server.Configuration.TLS) throws -> Server {
26+
let configuration: Server.Configuration = .init(
27+
target: .hostAndPort("localhost", 0),
28+
eventLoopGroup: self.eventLoopGroup,
29+
serviceProviders: [EchoProvider()],
30+
tls: tls
31+
)
32+
33+
return try Server.start(configuration: configuration).wait()
34+
}
35+
36+
func makeConnection(port: Int, tls: ClientConnection.Configuration.TLS) -> ClientConnection {
37+
let configuration: ClientConnection.Configuration = .init(
38+
target: .hostAndPort("localhost", port),
39+
eventLoopGroup: self.eventLoopGroup,
40+
tls: tls
41+
)
42+
43+
return ClientConnection(configuration: configuration)
44+
}
45+
46+
func doTestUnary() throws {
47+
let client = Echo_EchoServiceClient(connection: self.connection)
48+
let get = client.get(.with { $0.text = "foo" })
49+
50+
let response = try get.response.wait()
51+
XCTAssertEqual(response.text, "Swift echo get: foo")
52+
53+
let status = try get.status.wait()
54+
XCTAssertEqual(status.code, .ok)
55+
}
56+
57+
func testTLSWithHostnameOverride() throws {
58+
// Run a server presenting a certificate for example.com on localhost.
59+
let serverTLS: Server.Configuration.TLS = .init(
60+
certificateChain: [.certificate(SampleCertificate.exampleServer.certificate)],
61+
privateKey: .privateKey(SamplePrivateKey.exampleServer),
62+
trustRoots: .certificates([SampleCertificate.ca.certificate])
63+
)
64+
65+
self.server = try makeEchoServer(tls: serverTLS)
66+
guard let port = self.server.channel.localAddress?.port else {
67+
XCTFail("could not get server port")
68+
return
69+
}
70+
71+
let clientTLS: ClientConnection.Configuration.TLS = .init(
72+
trustRoots: .certificates([SampleCertificate.ca.certificate]),
73+
hostnameOverride: "example.com"
74+
)
75+
76+
self.connection = self.makeConnection(port: port, tls: clientTLS)
77+
try self.doTestUnary()
78+
}
79+
80+
func testTLSWithoutHostnameOverride() throws {
81+
// Run a server presenting a certificate for localhost on localhost.
82+
let serverTLS: Server.Configuration.TLS = .init(
83+
certificateChain: [.certificate(SampleCertificate.server.certificate)],
84+
privateKey: .privateKey(SamplePrivateKey.server),
85+
trustRoots: .certificates([SampleCertificate.ca.certificate])
86+
)
87+
88+
self.server = try makeEchoServer(tls: serverTLS)
89+
guard let port = self.server.channel.localAddress?.port else {
90+
XCTFail("could not get server port")
91+
return
92+
}
93+
94+
let clientTLS: ClientConnection.Configuration.TLS = .init(
95+
trustRoots: .certificates([SampleCertificate.ca.certificate])
96+
)
97+
98+
self.connection = self.makeConnection(port: port, tls: clientTLS)
99+
try self.doTestUnary()
100+
}
101+
}

Tests/GRPCTests/XCTestManifests.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,16 @@ extension ClientTLSFailureTests {
6363
]
6464
}
6565

66+
extension ClientTLSHostnameOverrideTests {
67+
// DO NOT MODIFY: This is autogenerated, use:
68+
// `swift test --generate-linuxmain`
69+
// to regenerate.
70+
static let __allTests__ClientTLSHostnameOverrideTests = [
71+
("testTLSWithHostnameOverride", testTLSWithHostnameOverride),
72+
("testTLSWithoutHostnameOverride", testTLSWithoutHostnameOverride),
73+
]
74+
}
75+
6676
extension ClientThrowingWhenServerReturningErrorTests {
6777
// DO NOT MODIFY: This is autogenerated, use:
6878
// `swift test --generate-linuxmain`
@@ -430,6 +440,7 @@ public func __allTests() -> [XCTestCaseEntry] {
430440
testCase(ClientClosedChannelTests.__allTests__ClientClosedChannelTests),
431441
testCase(ClientConnectionBackoffTests.__allTests__ClientConnectionBackoffTests),
432442
testCase(ClientTLSFailureTests.__allTests__ClientTLSFailureTests),
443+
testCase(ClientTLSHostnameOverrideTests.__allTests__ClientTLSHostnameOverrideTests),
433444
testCase(ClientThrowingWhenServerReturningErrorTests.__allTests__ClientThrowingWhenServerReturningErrorTests),
434445
testCase(ClientTimeoutTests.__allTests__ClientTimeoutTests),
435446
testCase(ConnectionBackoffTests.__allTests__ConnectionBackoffTests),

Tests/ca.crt

Lines changed: 0 additions & 16 deletions
This file was deleted.

Tests/client.crt

Lines changed: 0 additions & 16 deletions
This file was deleted.

Tests/client.pem

Lines changed: 0 additions & 28 deletions
This file was deleted.

Tests/server.crt

Lines changed: 0 additions & 16 deletions
This file was deleted.

Tests/server.pem

Lines changed: 0 additions & 28 deletions
This file was deleted.

0 commit comments

Comments
 (0)