diff --git a/protocol/src/main/resources/kaitai/channel_request_auth_agent_req_openssh.ksy b/protocol/src/main/resources/kaitai/channel_request_auth_agent_req_openssh.ksy new file mode 100644 index 000000000..89771f7da --- /dev/null +++ b/protocol/src/main/resources/kaitai/channel_request_auth_agent_req_openssh.ksy @@ -0,0 +1,4 @@ +meta: + id: channel_request_auth_agent_req_openssh + endian: be +doc-ref: RFC 9987 section 7.2 diff --git a/protocol/src/main/resources/kaitai/ssh.ksy b/protocol/src/main/resources/kaitai/ssh.ksy index 68709deeb..6288236c5 100644 --- a/protocol/src/main/resources/kaitai/ssh.ksy +++ b/protocol/src/main/resources/kaitai/ssh.ksy @@ -13,6 +13,7 @@ meta: - channel_open_session - channel_open_tun_openssh - channel_open_x11 + - channel_request_auth_agent_req_openssh - channel_request_env - channel_request_exec - channel_request_exit_signal diff --git a/protocol/src/main/resources/kaitai/ssh_msg_channel_request.ksy b/protocol/src/main/resources/kaitai/ssh_msg_channel_request.ksy index 535c157d5..16bce47cf 100644 --- a/protocol/src/main/resources/kaitai/ssh_msg_channel_request.ksy +++ b/protocol/src/main/resources/kaitai/ssh_msg_channel_request.ksy @@ -3,6 +3,7 @@ meta: endian: be imports: - ascii_string + - channel_request_auth_agent_req_openssh - channel_request_env - channel_request_exec - channel_request_exit_signal @@ -29,6 +30,7 @@ seq: switch-on: request_type.value cases: '"pty-req"': channel_request_pty_req + '"auth-agent-req@openssh.com"': channel_request_auth_agent_req_openssh '"x11-req"': channel_request_x11_req '"x11"': channel_request_x11 '"env"': channel_request_env diff --git a/sshlib/src/main/kotlin/org/connectbot/sshlib/SshClient.kt b/sshlib/src/main/kotlin/org/connectbot/sshlib/SshClient.kt index 823b36c76..8453f12af 100644 --- a/sshlib/src/main/kotlin/org/connectbot/sshlib/SshClient.kt +++ b/sshlib/src/main/kotlin/org/connectbot/sshlib/SshClient.kt @@ -419,8 +419,9 @@ class SshClient private constructor( /** * Enable SSH agent forwarding with the provided agent. * - * Must be called before opening sessions. When agent forwarding is enabled, - * remote servers can request signatures from your agent provider. + * Call after each successful [connect] and before [openSession]. Each session opened + * this way requests forwarding so the server can use your agent provider. + * Servers may decline forwarding. [openSftp] does not send a forwarding request. * * @param provider Agent implementation that handles signing requests */ diff --git a/sshlib/src/main/kotlin/org/connectbot/sshlib/blocking/BlockingSshClient.kt b/sshlib/src/main/kotlin/org/connectbot/sshlib/blocking/BlockingSshClient.kt index 7d1c5f861..ae2bd0507 100644 --- a/sshlib/src/main/kotlin/org/connectbot/sshlib/blocking/BlockingSshClient.kt +++ b/sshlib/src/main/kotlin/org/connectbot/sshlib/blocking/BlockingSshClient.kt @@ -245,8 +245,8 @@ class BlockingSshClient internal constructor( /** * Enable SSH agent forwarding with the provided agent. * - * Must be called before opening sessions. When agent forwarding is enabled, - * remote servers can request signatures from your agent provider. + * Call after each successful [connect] and before [openSession]. + * @see SshClient.enableAgentForwarding * * @param provider Agent implementation that handles signing requests */ diff --git a/sshlib/src/main/kotlin/org/connectbot/sshlib/client/SessionChannel.kt b/sshlib/src/main/kotlin/org/connectbot/sshlib/client/SessionChannel.kt index b294ed7c9..b6d1f4d7f 100644 --- a/sshlib/src/main/kotlin/org/connectbot/sshlib/client/SessionChannel.kt +++ b/sshlib/src/main/kotlin/org/connectbot/sshlib/client/SessionChannel.kt @@ -33,6 +33,7 @@ import org.connectbot.sshlib.SessionExit import org.connectbot.sshlib.SshException import org.connectbot.sshlib.SshSession import org.connectbot.sshlib.protocol.ByteString +import org.connectbot.sshlib.protocol.ChannelRequestAuthAgentReqOpenssh import org.connectbot.sshlib.protocol.ChannelRequestEnv import org.connectbot.sshlib.protocol.ChannelRequestExec import org.connectbot.sshlib.protocol.ChannelRequestPtyReq @@ -487,6 +488,12 @@ class SessionChannel internal constructor( } } + internal suspend fun requestAgentForwarding(): Boolean = performSendRequest { + connection.beginChannelRequest(_remoteChannelNumber, "auth-agent-req@openssh.com", wantReply = false) { msg -> + msg.setRequestSpecificFields(ChannelRequestAuthAgentReqOpenssh().apply { _check() }) + } + } + override suspend fun resizeTerminal( widthChars: Int, heightRows: Int, diff --git a/sshlib/src/main/kotlin/org/connectbot/sshlib/client/SshConnection.kt b/sshlib/src/main/kotlin/org/connectbot/sshlib/client/SshConnection.kt index 51e115dbe..3a4aa5f72 100644 --- a/sshlib/src/main/kotlin/org/connectbot/sshlib/client/SshConnection.kt +++ b/sshlib/src/main/kotlin/org/connectbot/sshlib/client/SshConnection.kt @@ -423,7 +423,7 @@ class SshConnection( private val nextLocalChannelNumber = AtomicInteger() private val channelRegistry = SshChannelRegistry() - private var agentProvider: AgentProvider? = null + @Volatile private var agentProvider: AgentProvider? = null private var serverHostKeyBlob: ByteArray? = null @Volatile private var serverAdvertisesHostBound: Boolean = false @@ -2010,9 +2010,8 @@ class SshConnection( /** * Enable SSH agent forwarding with the provided agent. * - * Must be called before the remote server opens agent channels. - * When agent forwarding is enabled, remote servers can request - * signatures from your agent provider. + * Call before opening session channels so they request forwarding. + * The provider also handles incoming agent channels on this connection. * * @param provider Agent implementation that handles signing requests */ @@ -2042,7 +2041,8 @@ class SshConnection( when (channelType) { "auth-agent@openssh.com" -> { - if (agentProvider == null) { + val provider = agentProvider + if (provider == null) { rejectChannelOpen(senderChannel, channelType) return } @@ -2062,7 +2062,7 @@ class SshConnection( sessionId = verifiedSessionId.copyOf(), serverHostKey = verifiedServerHostKey.copyOf(), ) - val handler = AgentProtocolHandler(agentProvider!!, sessionInfo) + val handler = AgentProtocolHandler(provider, sessionInfo) val agentChannel = AgentChannel( handler, this, @@ -3365,11 +3365,26 @@ class SshConnection( suspend fun openSessionChannel( initialWindowSize: Int = sessionWindowSize, maxPacketSize: Int = 32 * 1024, - ): SessionChannel? = openSessionChannel(initialWindowSize, maxPacketSize, bufferedStdout = false) + ): SessionChannel? = openSessionChannel( + initialWindowSize, + maxPacketSize, + bufferedStdout = false, + requestAgentForwarding = agentProvider != null, + ) - internal suspend fun openBufferedSessionChannel(initialWindowSize: Int): SessionChannel? = openSessionChannel(initialWindowSize, 32 * 1024, bufferedStdout = true) + internal suspend fun openBufferedSessionChannel(initialWindowSize: Int): SessionChannel? = openSessionChannel( + initialWindowSize, + 32 * 1024, + bufferedStdout = true, + requestAgentForwarding = false, + ) - private suspend fun openSessionChannel(initialWindowSize: Int, maxPacketSize: Int, bufferedStdout: Boolean): SessionChannel? { + private suspend fun openSessionChannel( + initialWindowSize: Int, + maxPacketSize: Int, + bufferedStdout: Boolean, + requestAgentForwarding: Boolean, + ): SessionChannel? { val localChannelNumber = allocateChannelNumber() logger.info("Opening session channel (local=$localChannelNumber)") @@ -3433,6 +3448,12 @@ class SshConnection( try { deferred.await() + val opened = channel ?: return null + if (requestAgentForwarding && !opened.requestAgentForwarding()) { + opened.close() + return null + } + return opened } catch (failure: Throwable) { if (admitted) { deferred.cancel() @@ -3442,8 +3463,6 @@ class SshConnection( } throw failure } - - return channel } internal suspend fun beginChannelRequest( diff --git a/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SessionEnvironmentTest.kt b/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SessionEnvironmentTest.kt index 5980b6cca..f71f9ad97 100644 --- a/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SessionEnvironmentTest.kt +++ b/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SessionEnvironmentTest.kt @@ -29,6 +29,7 @@ import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout +import org.connectbot.sshlib.AgentProvider import org.connectbot.sshlib.AuthResult import org.connectbot.sshlib.ConnectResult import org.connectbot.sshlib.HostKeyVerifier @@ -191,9 +192,11 @@ class SessionEnvironmentTest { } } - @Test - fun `SFTP defaults precede subsystem startup without awaiting env replies`(): Unit = runBlocking { + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `SFTP only sends environment defaults before subsystem startup`(agentForwarding: Boolean): Unit = runBlocking { fixture(mapOf("LANG" to "C")) { client, server -> + if (agentForwarding) client.enableAgentForwarding(mockk()) val opening = async { client.openSftp() } val open = server.awaitChannelOpen() server.sendChannelOpenConfirmation(open.senderChannel().toInt(), senderChannel = 100) diff --git a/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SshClientIntegrationTest.kt b/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SshClientIntegrationTest.kt index 74bc2a8f9..a33ab5f19 100644 --- a/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SshClientIntegrationTest.kt +++ b/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SshClientIntegrationTest.kt @@ -26,6 +26,10 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import kotlinx.coroutines.yield +import org.connectbot.sshlib.AgentIdentity +import org.connectbot.sshlib.AgentProvider +import org.connectbot.sshlib.AgentResult +import org.connectbot.sshlib.AgentSigningContext import org.connectbot.sshlib.AuthHandler import org.connectbot.sshlib.AuthPublicKey import org.connectbot.sshlib.AuthResult @@ -1690,6 +1694,34 @@ class SshClientIntegrationTest { } } + @Test + fun `agent forwarding creates a socket on initial connection and reconnect`() = runBlocking { + val client = SshClient(opensshContainer.host, acceptAllVerifier, opensshContainer.getMappedPort(22)) + val provider = object : AgentProvider { + override suspend fun getIdentities() = AgentResult.Success(emptyList()) + override suspend fun signData(context: AgentSigningContext) = AgentResult.Success(null) + } + + val exits = (1..2).map { + try { + withTimeout(10_000) { + assertIs(client.connect()) + assertIs(client.authenticatePassword(USERNAME, PASSWORD)) + client.enableAgentForwarding(provider) + assertNotNullValue(client.openSession()).use { session -> + assertTrue(session.requestPty()) + assertTrue(session.requestShell()) + session.write("test -S \"\$SSH_AUTH_SOCK\"; exit \$?\n".toByteArray()) + session.exitInfo.await() + } + } + } finally { + client.disconnect() + } + } + assertEquals(listOf(SessionExit.Status(0), SessionExit.Status(0)), exits) + } + @Test fun `should support opening multiple session channels sequentially on single connection`() = runBlocking { val host = opensshContainer.host diff --git a/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SshConnectionFlowTest.kt b/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SshConnectionFlowTest.kt index 524fb8d5f..f56fbff28 100644 --- a/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SshConnectionFlowTest.kt +++ b/sshlib/src/test/kotlin/org/connectbot/sshlib/client/SshConnectionFlowTest.kt @@ -48,6 +48,7 @@ import org.connectbot.sshlib.PublicKey import org.connectbot.sshlib.SessionExit import org.connectbot.sshlib.crypto.PrivateKeyReader import org.connectbot.sshlib.crypto.SshPublicKeyEncoder +import org.connectbot.sshlib.protocol.ChannelRequestAuthAgentReqOpenssh import org.connectbot.sshlib.protocol.ChannelRequestShell import org.connectbot.sshlib.protocol.SshEnums import org.connectbot.sshlib.transport.PipedTransport @@ -506,6 +507,36 @@ class SshConnectionFlowTest { } } + @Test + fun `enabled agent forwarding is requested before PTY and shell`() = runTest { + connectedFixture { connection, server, dispatcher -> + authenticate(connection, server, dispatcher) + connection.enableAgentForwarding( + object : AgentProvider { + override suspend fun getIdentities() = AgentResult.Success(emptyList()) + override suspend fun signData(context: AgentSigningContext) = AgentResult.Success(null) + }, + ) + val session = openSession(connection, server, dispatcher, remoteChannelNumber = 200) + val pty = async(dispatcher) { session.requestPty() } + val forwarding = withTimeout(5_000) { server.awaitChannelRequest() } + assertEquals("auth-agent-req@openssh.com", forwarding.requestType().value()) + assertEquals(200L, forwarding.recipientChannel()) + assertEquals(0, forwarding.wantReply()) + assertIs(forwarding.requestSpecificFields()) + assertTrue(forwarding._io().isEof) + + assertEquals("pty-req", withTimeout(5_000) { server.awaitChannelRequest() }.requestType().value()) + server.sendChannelSuccess(session.localChannelNumber) + assertTrue(withTimeout(5_000) { pty.await() }) + + val shell = async(dispatcher) { session.requestShell() } + assertEquals("shell", withTimeout(5_000) { server.awaitChannelRequest() }.requestType().value()) + server.sendChannelSuccess(session.localChannelNumber) + assertTrue(withTimeout(5_000) { shell.await() }) + } + } + @Test fun `session channel open returns null on open failure`() = runTest { connectedFixture { connection, server, dispatcher ->