Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
meta:
id: channel_request_auth_agent_req_openssh
endian: be
doc-ref: RFC 9987 section 7.2
1 change: 1 addition & 0 deletions protocol/src/main/resources/kaitai/ssh.ksy
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions sshlib/src/main/kotlin/org/connectbot/sshlib/SshClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@
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
Expand Down Expand Up @@ -1056,9 +1056,9 @@
}
}
when (result) {
is InternalAuthResult.Success -> return PublicAuthResult.Success

Check warning on line 1059 in sshlib/src/main/kotlin/org/connectbot/sshlib/client/SshConnection.kt

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this useless is check.

See more on https://sonarcloud.io/project/issues?id=connectbot_cbssh&issues=AaIEjn8-SZVHGneKvwEq&open=AaIEjn8-SZVHGneKvwEq&pullRequest=443

is InternalAuthResult.Failure -> {

Check warning on line 1061 in sshlib/src/main/kotlin/org/connectbot/sshlib/client/SshConnection.kt

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this useless is check.

See more on https://sonarcloud.io/project/issues?id=connectbot_cbssh&issues=AaIEjn8-SZVHGneKvwEr&open=AaIEjn8-SZVHGneKvwEr&pullRequest=443
allowedAuthentications = result.allowedMethods
if (result.partialSuccess) {
// Previously rejected keys can become valid for the next factor,
Expand Down Expand Up @@ -2010,9 +2010,8 @@
/**
* 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
*/
Expand Down Expand Up @@ -2042,7 +2041,8 @@

when (channelType) {
"auth-agent@openssh.com" -> {
if (agentProvider == null) {
val provider = agentProvider
if (provider == null) {
rejectChannelOpen(senderChannel, channelType)
return
}
Expand All @@ -2062,7 +2062,7 @@
sessionId = verifiedSessionId.copyOf(),
serverHostKey = verifiedServerHostKey.copyOf(),
)
val handler = AgentProtocolHandler(agentProvider!!, sessionInfo)
val handler = AgentProtocolHandler(provider, sessionInfo)
val agentChannel = AgentChannel(
handler,
this,
Expand Down Expand Up @@ -3365,11 +3365,26 @@
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)")
Expand Down Expand Up @@ -3433,6 +3448,12 @@

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()
Expand All @@ -3442,8 +3463,6 @@
}
throw failure
}

return channel
}

internal suspend fun beginChannelRequest(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<AgentProvider>())
val opening = async { client.openSftp() }
val open = server.awaitChannelOpen()
server.sendChannelOpenConfirmation(open.senderChannel().toInt(), senderChannel = 100)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<AgentIdentity>())
override suspend fun signData(context: AgentSigningContext) = AgentResult.Success(null)
}

val exits = (1..2).map {
try {
withTimeout(10_000) {
assertIs<ConnectResult.Success>(client.connect())
assertIs<AuthResult.Success>(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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<AgentIdentity>())
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<ChannelRequestAuthAgentReqOpenssh>(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 ->
Expand Down
Loading