-
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathLibSSH2TunnelFactory.swift
More file actions
862 lines (753 loc) · 33.6 KB
/
LibSSH2TunnelFactory.swift
File metadata and controls
862 lines (753 loc) · 33.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
//
// LibSSH2TunnelFactory.swift
// TablePro
//
import Foundation
import os
import CLibSSH2
/// Credentials needed for SSH tunnel creation
internal struct SSHTunnelCredentials: Sendable {
let sshPassword: String?
let keyPassphrase: String?
let totpSecret: String?
let totpProvider: (any TOTPProvider)?
}
/// Creates fully-connected and authenticated SSH tunnels using libssh2.
internal enum LibSSH2TunnelFactory {
private static let logger = Logger(subsystem: "com.TablePro", category: "LibSSH2TunnelFactory")
private static let connectionTimeout: Int32 = 10 // seconds
// MARK: - Global Init
private static let initialized: Bool = {
libssh2_init(0)
return true
}()
// MARK: - Public
static func createTunnel(
connectionId: UUID,
config: SSHConfiguration,
credentials: SSHTunnelCredentials,
remoteHost: String,
remotePort: Int,
localPort: Int
) async throws -> LibSSH2Tunnel {
_ = initialized
let chain = try await buildAuthenticatedChain(
config: config,
credentials: credentials,
queueLabel: "com.TablePro.ssh.hop.\(connectionId.uuidString)"
)
do {
// Bind local listening socket
let listenFD = try bindListenSocket(port: localPort)
let tunnel = LibSSH2Tunnel(
connectionId: connectionId,
localPort: localPort,
session: chain.session,
socketFD: chain.socketFD,
listenFD: listenFD,
jumpChain: chain.jumpHops.map { hop in
LibSSH2Tunnel.JumpHop(
session: hop.session,
socket: hop.socket,
channel: hop.channel,
relayTask: hop.relayTask
)
}
)
logger.info(
"Tunnel created: \(config.host) -> 127.0.0.1:\(localPort) -> \(remoteHost):\(remotePort)"
)
return tunnel
} catch {
cleanupChain(chain, reason: "Error")
throw error
}
}
/// Test SSH connectivity without creating a full tunnel.
/// Connects, performs handshake, verifies host key, authenticates, then cleans up.
static func testConnection(
config: SSHConfiguration,
credentials: SSHTunnelCredentials
) async throws {
_ = initialized
let chain = try await buildAuthenticatedChain(
config: config,
credentials: credentials,
queueLabel: "com.TablePro.ssh.test-hop"
)
logger.info("SSH test connection successful to \(config.host)")
cleanupChain(chain, reason: "Test complete")
}
// MARK: - Shared Chain Builder
/// Result of building an authenticated SSH chain (possibly through jump hosts).
private struct AuthenticatedChain {
let session: OpaquePointer
let socketFD: Int32
let initialSocketFD: Int32
let jumpHops: [HopInfo]
struct HopInfo {
let session: OpaquePointer
let socket: Int32
let channel: OpaquePointer
let relayTask: Task<Void, Never>?
}
}
private static func buildAuthenticatedChain(
config: SSHConfiguration,
credentials: SSHTunnelCredentials,
queueLabel: String
) async throws -> AuthenticatedChain {
let document = await SSHConfigCache.shared.current()
let resolvedPrimary = SSHConfigResolver.resolve(config, document: document)
let formJumps = config.jumpHosts
let resolvedJumps: [ResolvedSSHTarget] = (formJumps.isEmpty ? resolvedPrimary.proxyJump : formJumps)
.map { SSHConfigResolver.resolve($0, document: document) }
if resolvedPrimary.username.isEmpty {
throw SSHTunnelError.tunnelCreationFailed(
"SSH username not set. Add it to the form or set `User` for `\(config.host)` in ~/.ssh/config."
)
}
let firstHop = resolvedJumps.first ?? resolvedPrimary
let socketFD = try connectTCP(host: firstHop.host, port: firstHop.port)
do {
let session = try createSession(socketFD: socketFD)
var jumpHops: [AuthenticatedChain.HopInfo] = []
var currentSession = session
var currentSocketFD = socketFD
do {
try await verifyHostKey(session: session, hostname: firstHop.host, port: firstHop.port)
if !resolvedJumps.isEmpty {
let jumpAuthenticator = try buildJumpAuthenticator(
jumpHost: formJumps.first ?? SSHJumpHost(),
resolved: resolvedJumps[0]
)
try jumpAuthenticator.authenticate(session: session, username: resolvedJumps[0].username)
} else {
let authenticator = try buildAuthenticator(
config: config,
resolved: resolvedPrimary,
credentials: credentials
)
try authenticator.authenticate(session: session, username: resolvedPrimary.username)
}
if !resolvedJumps.isEmpty {
for jumpIndex in 0..<resolvedJumps.count {
let nextResolved: ResolvedSSHTarget = jumpIndex + 1 < resolvedJumps.count
? resolvedJumps[jumpIndex + 1]
: resolvedPrimary
let channel = try openChannel(
session: currentSession,
socketFD: currentSocketFD,
remoteHost: nextResolved.host,
remotePort: nextResolved.port
)
var fds: [Int32] = [0, 0]
guard socketpair(AF_UNIX, SOCK_STREAM, 0, &fds) == 0 else {
libssh2_channel_free(channel)
throw SSHTunnelError.tunnelCreationFailed("Failed to create socketpair")
}
let hopSessionQueue = DispatchQueue(
label: "\(queueLabel).\(jumpIndex)",
qos: .utility
)
let relayTask = startChannelRelay(
channel: channel,
socketFD: fds[0],
sshSocketFD: currentSocketFD,
session: currentSession,
sessionQueue: hopSessionQueue
)
let hop = AuthenticatedChain.HopInfo(
session: currentSession,
socket: currentSocketFD,
channel: channel,
relayTask: relayTask
)
jumpHops.append(hop)
let nextSession: OpaquePointer
do {
nextSession = try createSession(socketFD: fds[1])
} catch {
Darwin.close(fds[1])
relayTask.cancel()
throw error
}
do {
try await verifyHostKey(
session: nextSession,
hostname: nextResolved.host,
port: nextResolved.port
)
if jumpIndex + 1 < resolvedJumps.count {
let nextFormJump = formJumps.indices.contains(jumpIndex + 1)
? formJumps[jumpIndex + 1]
: SSHJumpHost()
let jumpAuth = try buildJumpAuthenticator(
jumpHost: nextFormJump,
resolved: nextResolved
)
try jumpAuth.authenticate(
session: nextSession,
username: nextResolved.username
)
} else {
let authenticator = try buildAuthenticator(
config: config,
resolved: resolvedPrimary,
credentials: credentials
)
try authenticator.authenticate(
session: nextSession,
username: resolvedPrimary.username
)
}
} catch {
// Clean up nextSession and fds[1]; relay task owns fds[0]
tablepro_libssh2_session_disconnect(nextSession, "Error")
libssh2_session_free(nextSession)
Darwin.close(fds[1])
relayTask.cancel()
throw error
}
currentSession = nextSession
currentSocketFD = fds[1]
}
}
return AuthenticatedChain(
session: currentSession,
socketFD: currentSocketFD,
initialSocketFD: socketFD,
jumpHops: jumpHops
)
} catch {
// Clean up currentSession if it differs from all hop sessions
// (happens when a nextSession was created but failed auth/verify)
let sessionInHops = jumpHops.contains { $0.session == currentSession }
if !sessionInHops {
tablepro_libssh2_session_disconnect(currentSession, "Error")
libssh2_session_free(currentSession)
if currentSocketFD != socketFD {
Darwin.close(currentSocketFD)
}
}
// Clean up any jump hops that were created (reverse order).
// Shutdown sockets first to break relay loops, then free resources.
for hop in jumpHops.reversed() {
hop.relayTask?.cancel()
shutdown(hop.socket, SHUT_RDWR)
}
for hop in jumpHops.reversed() {
libssh2_channel_free(hop.channel)
tablepro_libssh2_session_disconnect(hop.session, "Error")
libssh2_session_free(hop.session)
Darwin.close(hop.socket)
}
throw error
}
} catch {
Darwin.close(socketFD)
throw error
}
}
/// Clean up all resources in an authenticated chain.
private static func cleanupChain(_ chain: AuthenticatedChain, reason: String) {
// Disconnect the final session
tablepro_libssh2_session_disconnect(chain.session, reason)
libssh2_session_free(chain.session)
if chain.socketFD != chain.initialSocketFD {
Darwin.close(chain.socketFD)
}
// Clean up jump hops in reverse order:
// First pass: cancel relays and shutdown sockets to break relay loops
for hop in chain.jumpHops.reversed() {
hop.relayTask?.cancel()
shutdown(hop.socket, SHUT_RDWR)
}
// Second pass: free channels, sessions, and close sockets
// Note: relay task owns fds[0] via defer, so we only close hop.socket
// (which is the SSH socket for that hop, not the relay socketpair fd)
for hop in chain.jumpHops.reversed() {
libssh2_channel_free(hop.channel)
tablepro_libssh2_session_disconnect(hop.session, reason)
libssh2_session_free(hop.session)
Darwin.close(hop.socket)
}
}
// MARK: - TCP Connection
private static func connectTCP(host: String, port: Int) throws -> Int32 {
var hints = addrinfo()
hints.ai_family = AF_UNSPEC
hints.ai_socktype = SOCK_STREAM
hints.ai_protocol = IPPROTO_TCP
var result: UnsafeMutablePointer<addrinfo>?
let portString = String(port)
let rc = getaddrinfo(host, portString, &hints, &result)
guard rc == 0, let firstAddr = result else {
let errorMsg = rc != 0 ? String(cString: gai_strerror(rc)) : "No address found"
throw SSHTunnelError.tunnelCreationFailed("DNS resolution failed for \(host): \(errorMsg)")
}
defer { freeaddrinfo(result) }
// Iterate through all addresses returned by getaddrinfo
var currentAddr: UnsafeMutablePointer<addrinfo>? = firstAddr
var lastError: String = "No address found"
while let addrInfo = currentAddr {
let fd = socket(addrInfo.pointee.ai_family, addrInfo.pointee.ai_socktype, addrInfo.pointee.ai_protocol)
guard fd >= 0 else {
currentAddr = addrInfo.pointee.ai_next
continue
}
// Set non-blocking for connection timeout
let flags = fcntl(fd, F_GETFL, 0)
fcntl(fd, F_SETFL, flags | O_NONBLOCK)
let connectResult = connect(fd, addrInfo.pointee.ai_addr, addrInfo.pointee.ai_addrlen)
if connectResult != 0 && errno != EINPROGRESS {
Darwin.close(fd)
lastError = "Connection to \(host):\(port) failed"
currentAddr = addrInfo.pointee.ai_next
continue
}
if connectResult != 0 {
// Wait for connection with timeout using poll()
var writePollFD = pollfd(fd: fd, events: Int16(POLLOUT), revents: 0)
let pollResult = poll(&writePollFD, 1, connectionTimeout * 1_000)
if pollResult <= 0 {
Darwin.close(fd)
lastError = "Connection timed out"
currentAddr = addrInfo.pointee.ai_next
continue
}
// Check for connection error
var socketError: Int32 = 0
var errorLen = socklen_t(MemoryLayout<Int32>.size)
getsockopt(fd, SOL_SOCKET, SO_ERROR, &socketError, &errorLen)
if socketError != 0 {
Darwin.close(fd)
lastError = "Connection to \(host):\(port) failed: \(String(cString: strerror(socketError)))"
currentAddr = addrInfo.pointee.ai_next
continue
}
}
// Restore blocking mode for handshake/auth
fcntl(fd, F_SETFL, flags)
// Enable OS-level TCP keepalive so the kernel detects dead connections
// (e.g., silent NAT gateway timeout on AWS) independently of libssh2's
// application-level keepalive. macOS uses TCP_KEEPALIVE for the idle
// interval (seconds before the first keepalive probe).
var yes: Int32 = 1
if setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, socklen_t(MemoryLayout<Int32>.size)) != 0 {
logger.warning("Failed to set SO_KEEPALIVE: \(String(cString: strerror(errno)))")
}
var keepIdle: Int32 = 60
if setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &keepIdle, socklen_t(MemoryLayout<Int32>.size)) != 0 {
logger.warning("Failed to set TCP_KEEPALIVE: \(String(cString: strerror(errno)))")
}
logger.debug("TCP connected to \(host):\(port)")
return fd
}
throw SSHTunnelError.tunnelCreationFailed(lastError)
}
// MARK: - Session
private static func createSession(socketFD: Int32) throws -> OpaquePointer {
guard let session = tablepro_libssh2_session_init() else {
throw SSHTunnelError.tunnelCreationFailed("Failed to initialize libssh2 session")
}
libssh2_session_set_blocking(session, 1)
let rc = libssh2_session_handshake(session, socketFD)
if rc != 0 {
var msgPtr: UnsafeMutablePointer<CChar>?
var msgLen: Int32 = 0
libssh2_session_last_error(session, &msgPtr, &msgLen, 0)
let detail = msgPtr.map { String(cString: $0) } ?? "Unknown error"
libssh2_session_free(session)
throw SSHTunnelError.tunnelCreationFailed("SSH handshake failed: \(detail)")
}
return session
}
// MARK: - Host Key Verification
private static func verifyHostKey(
session: OpaquePointer,
hostname: String,
port: Int
) async throws {
var keyLength = 0
var keyType: Int32 = 0
guard let keyPtr = libssh2_session_hostkey(session, &keyLength, &keyType) else {
throw SSHTunnelError.tunnelCreationFailed("Failed to get host key")
}
let keyData = Data(bytes: keyPtr, count: keyLength)
let keyTypeName = HostKeyStore.keyTypeName(keyType)
try await HostKeyVerifier.verify(
keyData: keyData,
keyType: keyTypeName,
hostname: hostname,
port: port
)
}
// MARK: - Authentication
private static func buildAuthenticator(
config: SSHConfiguration,
resolved: ResolvedSSHTarget,
credentials: SSHTunnelCredentials
) throws -> any SSHAuthenticator {
switch config.authMethod {
case .password where config.totpMode != .none:
guard let sshPassword = credentials.sshPassword else {
logger.error("SSH password is nil (Keychain lookup may have failed) for \(resolved.host)")
throw SSHTunnelError.authenticationFailed
}
let totpProvider = buildTOTPProvider(config: config, credentials: credentials)
return CompositeAuthenticator(authenticators: [
PasswordAuthenticator(password: sshPassword),
KeyboardInteractiveAuthenticator(password: nil, totpProvider: totpProvider),
])
case .password:
guard let sshPassword = credentials.sshPassword else {
logger.error("SSH password is nil (Keychain lookup may have failed) for \(resolved.host)")
throw SSHTunnelError.authenticationFailed
}
return PasswordAuthenticator(password: sshPassword)
case .privateKey:
let keyPaths = effectiveKeyPaths(for: resolved)
guard !keyPaths.isEmpty else {
throw SSHTunnelError.authenticationFailed
}
var authenticators: [any SSHAuthenticator] = keyPaths.map { keyPath in
buildKeyFileAuthenticator(
keyPath: keyPath,
providedPassphrase: credentials.keyPassphrase,
resolved: resolved,
canPrompt: true
)
}
if config.totpMode != .none {
authenticators.append(KeyboardInteractiveAuthenticator(
password: nil,
totpProvider: buildTOTPProvider(config: config, credentials: credentials)
))
}
return authenticators.count == 1
? authenticators[0]
: CompositeAuthenticator(authenticators: authenticators)
case .sshAgent:
let socketPath: String? = resolved.agentSocketPath.isEmpty
? nil
: SSHPathUtilities.expandTilde(resolved.agentSocketPath)
var authenticators: [any SSHAuthenticator] = [AgentAuthenticator(socketPath: socketPath)]
for keyPath in effectiveKeyPaths(for: resolved) {
authenticators.append(buildKeyFileAuthenticator(
keyPath: keyPath,
providedPassphrase: credentials.keyPassphrase,
resolved: resolved,
canPrompt: true
))
}
if config.totpMode != .none {
authenticators.append(KeyboardInteractiveAuthenticator(
password: nil,
totpProvider: buildTOTPProvider(config: config, credentials: credentials)
))
}
return authenticators.count == 1
? authenticators[0]
: CompositeAuthenticator(authenticators: authenticators)
case .keyboardInteractive:
let totpProvider = buildTOTPProvider(config: config, credentials: credentials)
return KeyboardInteractiveAuthenticator(
password: credentials.sshPassword,
totpProvider: totpProvider
)
}
}
private static func effectiveKeyPaths(for resolved: ResolvedSSHTarget) -> [String] {
if !resolved.identityFiles.isEmpty {
return resolved.identityFiles
}
if resolved.identitiesOnly {
return []
}
let sshDir = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".ssh", isDirectory: true)
return ["id_ed25519", "id_rsa", "id_ecdsa"]
.map { sshDir.appendingPathComponent($0).path }
.filter { FileManager.default.isReadableFile(atPath: $0) }
}
/// Passphrase resolution is deferred to auth time (not build time) so
/// that, when this authenticator is used as an agent fallback, the user
/// is only prompted if the agent actually fails.
private static func buildKeyFileAuthenticator(
keyPath: String,
providedPassphrase: String?,
resolved: ResolvedSSHTarget,
canPrompt: Bool
) -> any SSHAuthenticator {
KeyFileAuthenticator(
keyPath: keyPath,
providedPassphrase: providedPassphrase,
canPrompt: canPrompt,
useKeychain: resolved.useKeychain,
addKeysToAgent: resolved.addKeysToAgent
)
}
/// Authenticator that resolves the passphrase at AUTH time (not build time),
/// then delegates to PublicKeyAuthenticator. Saves to Keychain and adds to
/// agent only after authentication succeeds.
private struct KeyFileAuthenticator: SSHAuthenticator {
let keyPath: String
let providedPassphrase: String?
let canPrompt: Bool
let useKeychain: Bool
let addKeysToAgent: Bool
func authenticate(session: OpaquePointer, username: String) throws {
let expandedPath = SSHPathUtilities.expandTilde(keyPath)
// 1. Try with stored passphrase or nil (covers unencrypted keys + Keychain hits)
let storedPassphrase = SSHPassphraseResolver.resolve(
forKeyAt: keyPath,
provided: providedPassphrase,
useKeychain: useKeychain
)
let firstAttempt = PublicKeyAuthenticator(
privateKeyPath: keyPath,
passphrase: storedPassphrase
)
do {
try firstAttempt.authenticate(session: session, username: username)
addToAgentIfNeeded(path: expandedPath)
return
} catch {
// Auth failed — key likely needs a passphrase we don't have yet
}
// 2. Prompt the user if allowed (key is encrypted, no stored passphrase)
guard canPrompt else { throw SSHTunnelError.authenticationFailed }
let provider = PromptPassphraseProvider(keyPath: expandedPath)
guard let promptResult = provider.providePassphrase() else {
throw SSHTunnelError.authenticationFailed
}
let retryAuth = PublicKeyAuthenticator(
privateKeyPath: keyPath,
passphrase: promptResult.passphrase
)
try retryAuth.authenticate(session: session, username: username)
// Auth succeeded — save to Keychain if user opted in
if promptResult.saveToKeychain && useKeychain {
SSHKeychainLookup.savePassphrase(promptResult.passphrase, forKeyAt: expandedPath)
}
addToAgentIfNeeded(path: expandedPath)
}
private func addToAgentIfNeeded(path: String) {
guard addKeysToAgent else { return }
DispatchQueue.global(qos: .utility).async {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/ssh-add")
// Use --apple-use-keychain so ssh-add reads the passphrase from
// Keychain for encrypted keys (no TTY available in GUI apps)
process.arguments = ["--apple-use-keychain", path]
process.standardOutput = FileHandle.nullDevice
process.standardError = FileHandle.nullDevice
try? process.run()
process.waitUntilExit()
}
}
}
private static func buildJumpAuthenticator(
jumpHost: SSHJumpHost,
resolved: ResolvedSSHTarget
) throws -> any SSHAuthenticator {
switch jumpHost.authMethod {
case .privateKey:
let keyPaths = effectiveKeyPaths(for: resolved)
guard !keyPaths.isEmpty else {
throw SSHTunnelError.authenticationFailed
}
let authenticators = keyPaths.map { path in
KeyFileAuthenticator(
keyPath: path,
providedPassphrase: nil,
canPrompt: true,
useKeychain: resolved.useKeychain,
addKeysToAgent: resolved.addKeysToAgent
)
}
return authenticators.count == 1
? authenticators[0]
: CompositeAuthenticator(authenticators: authenticators)
case .sshAgent:
let socketPath: String? = resolved.agentSocketPath.isEmpty ? nil : resolved.agentSocketPath
let agent = AgentAuthenticator(socketPath: socketPath)
if !jumpHost.privateKeyPath.isEmpty {
let keyAuth = KeyFileAuthenticator(
keyPath: jumpHost.privateKeyPath,
providedPassphrase: nil,
canPrompt: true,
useKeychain: resolved.useKeychain,
addKeysToAgent: resolved.addKeysToAgent
)
return CompositeAuthenticator(authenticators: [agent, keyAuth])
}
return agent
}
}
private static func buildTOTPProvider(
config: SSHConfiguration,
credentials: SSHTunnelCredentials
) -> (any TOTPProvider)? {
switch config.totpMode {
case .none:
return nil
case .autoGenerate:
guard let secret = credentials.totpSecret,
let generator = TOTPGenerator.fromBase32Secret(
secret,
algorithm: config.totpAlgorithm.toGeneratorAlgorithm,
digits: config.totpDigits,
period: config.totpPeriod
) else {
return nil
}
return AutoTOTPProvider(generator: generator)
case .promptAtConnect:
return credentials.totpProvider ?? PromptTOTPProvider()
}
}
// MARK: - Channel Operations
private static func openChannel(
session: OpaquePointer,
socketFD: Int32,
remoteHost: String,
remotePort: Int
) throws -> OpaquePointer {
// Use blocking mode for channel open during setup
libssh2_session_set_blocking(session, 1)
defer { libssh2_session_set_blocking(session, 0) }
guard let channel = libssh2_channel_direct_tcpip_ex(
session,
remoteHost,
Int32(remotePort),
"127.0.0.1",
0
) else {
throw SSHTunnelError.channelOpenFailed
}
return channel
}
/// Start a relay task that copies data between a channel and a socketpair fd.
/// libssh2 calls use `sessionQueue.sync` for thread safety; I/O loop runs on a concurrent queue.
private static func startChannelRelay(
channel: OpaquePointer,
socketFD: Int32,
sshSocketFD: Int32,
session: OpaquePointer,
sessionQueue: DispatchQueue
) -> Task<Void, Never> {
let relayQueue = DispatchQueue(
label: "com.TablePro.ssh.hop-relay",
qos: .utility
)
return Task.detached {
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
relayQueue.async {
let bufferSize = 32_768
let buffer = UnsafeMutablePointer<CChar>.allocate(capacity: bufferSize)
defer {
buffer.deallocate()
Darwin.close(socketFD)
continuation.resume()
}
while !Task.isCancelled {
var pollFDs = [
pollfd(fd: socketFD, events: Int16(POLLIN), revents: 0),
pollfd(fd: sshSocketFD, events: Int16(POLLIN), revents: 0),
]
let pollResult = poll(&pollFDs, 2, 500)
if pollResult < 0 { break }
// Channel -> socketpair (serialized libssh2 call)
if pollFDs[1].revents & Int16(POLLIN) != 0 || pollResult == 0 {
let channelRead: Int = sessionQueue.sync {
Int(tablepro_libssh2_channel_read(channel, buffer, bufferSize))
}
if channelRead > 0 {
var totalSent = 0
while totalSent < channelRead {
let sent = send(
socketFD,
buffer.advanced(by: totalSent),
channelRead - totalSent,
0
)
if sent <= 0 { return }
totalSent += sent
}
} else if channelRead == 0
|| sessionQueue.sync(execute: { libssh2_channel_eof(channel) }) != 0 {
return
} else if channelRead != Int(LIBSSH2_ERROR_EAGAIN) {
return
}
}
// Socketpair -> channel
if pollFDs[0].revents & Int16(POLLIN) != 0 {
let socketRead = recv(socketFD, buffer, bufferSize, 0)
if socketRead <= 0 { return }
var totalWritten = 0
while totalWritten < Int(socketRead) {
let written: Int = sessionQueue.sync {
Int(tablepro_libssh2_channel_write(
channel,
buffer.advanced(by: totalWritten),
Int(socketRead) - totalWritten
))
}
if written > 0 {
totalWritten += written
} else if written == Int(LIBSSH2_ERROR_EAGAIN) {
var writePollFD = pollfd(
fd: sshSocketFD, events: Int16(POLLOUT), revents: 0
)
_ = poll(&writePollFD, 1, 1_000)
} else {
return
}
}
}
}
}
}
}
}
// MARK: - Local Socket
private static func bindListenSocket(port: Int) throws -> Int32 {
let listenFD = socket(AF_INET, SOCK_STREAM, 0)
guard listenFD >= 0 else {
throw SSHTunnelError.tunnelCreationFailed("Failed to create listening socket")
}
var reuseAddr: Int32 = 1
setsockopt(listenFD, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, socklen_t(MemoryLayout<Int32>.size))
var addr = sockaddr_in()
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = in_port_t(port).bigEndian
addr.sin_addr.s_addr = inet_addr("127.0.0.1")
let bindResult = withUnsafePointer(to: &addr) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
bind(listenFD, $0, socklen_t(MemoryLayout<sockaddr_in>.size))
}
}
guard bindResult == 0 else {
Darwin.close(listenFD)
throw SSHTunnelError.tunnelCreationFailed("Port \(port) already in use")
}
guard listen(listenFD, 5) == 0 else {
Darwin.close(listenFD)
throw SSHTunnelError.tunnelCreationFailed("Failed to listen on port \(port)")
}
return listenFD
}
}
// MARK: - TOTPAlgorithm Extension
extension TOTPAlgorithm {
var toGeneratorAlgorithm: TOTPGenerator.Algorithm {
switch self {
case .sha1: return .sha1
case .sha256: return .sha256
case .sha512: return .sha512
}
}
}