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
Expand Up @@ -172,6 +172,7 @@
import java.security.SecureRandom
import java.util.Collections
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import kotlin.coroutines.CoroutineContext
import org.connectbot.sshlib.AuthResult as PublicAuthResult
Expand Down Expand Up @@ -343,9 +344,9 @@
override suspend fun sendKexInit() = this@SshConnection.sendKexInit()
override fun receiveKexInit(msg: SshMsgKexinit, initialExchange: Boolean) = this@SshConnection.receiveKexInit(msg, initialExchange)
override suspend fun sendKexExchangeInit() = this@SshConnection.sendKexExchangeInit()
override suspend fun receiveKexDhReply(msg: SshMsgKexdhReply) = this@SshConnection.receiveKexDhReply(msg)
override suspend fun receiveKexEcdhReply(msg: SshMsgKexEcdhReply) = this@SshConnection.receiveKexEcdhReply(msg)
override suspend fun receiveKexDhGexReply(msg: SshMsgKexDhGexReply) = this@SshConnection.receiveKexDhGexReply(msg)
override fun receiveKexDhReply(msg: SshMsgKexdhReply) = this@SshConnection.receiveKexDhReply(msg)
override fun receiveKexEcdhReply(msg: SshMsgKexEcdhReply) = this@SshConnection.receiveKexEcdhReply(msg)
override fun receiveKexDhGexReply(msg: SshMsgKexDhGexReply) = this@SshConnection.receiveKexDhGexReply(msg)
override fun isRekeying(): Boolean = this@SshConnection.isRekeying
override fun isAuthenticationRequestPending(): Boolean = this@SshConnection.authRequestPending
override fun authenticationRequestStarted() {
Expand Down Expand Up @@ -419,8 +420,7 @@
private var serverExtInfoReceivedCount: Int = 0
private var clientExtInfoSent: Boolean = false

private var nextLocalChannelNumber = 0
private val channelNumberLock = Mutex()
private val nextLocalChannelNumber = AtomicInteger()
private val channelRegistry = SshChannelRegistry()

private var agentProvider: AgentProvider? = null
Expand Down Expand Up @@ -597,7 +597,7 @@
setData(createByteString(byteArrayOf()))
_check()
}
writePacket(SshEnums.MessageType.SSH_MSG_IGNORE.id().toInt(), msg.toByteArray())
writePacket(SshEnums.MessageType.SSH_MSG_IGNORE.id().toInt(), msg.toByteArray(4))
}

/** Each connection owns its heartbeat, which is retired with its transport. */
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=AaIEZTroJwCs2b2g2-gP&open=AaIEZTroJwCs2b2g2-gP&pullRequest=442

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=AaIEZTroJwCs2b2g2-gQ&open=AaIEZTroJwCs2b2g2-gQ&pullRequest=442
allowedAuthentications = result.allowedMethods
if (result.partialSuccess) {
// Previously rejected keys can become valid for the next factor,
Expand Down Expand Up @@ -1529,7 +1529,7 @@
)
}

private suspend fun receiveKexDhReply(msg: SshMsgKexdhReply) {
private fun receiveKexDhReply(msg: SshMsgKexdhReply) {
logger.info("Received DH_REPLY from server")
completeKex(
serverHostKey = msg.serverKey().data(),
Expand All @@ -1538,7 +1538,7 @@
)
}

private suspend fun receiveKexEcdhReply(msg: SshMsgKexEcdhReply) {
private fun receiveKexEcdhReply(msg: SshMsgKexEcdhReply) {
logger.info("Received ECDH_REPLY from server")
try {
completeKex(
Expand All @@ -1552,7 +1552,7 @@
}
}

private suspend fun completeKex(serverHostKey: ByteArray, serverPublicKey: ByteArray, signature: ByteArray) {
private fun completeKex(serverHostKey: ByteArray, serverPublicKey: ByteArray, signature: ByteArray) {
val kexAlg = kex ?: throw SshException(ERROR_NO_KEX_ALGORITHM_INITIALIZED)
val sv = serverVersion ?: throw SshException("Server version not received")
val cki = clientKexInit ?: throw SshException("Client KEX_INIT not sent")
Expand Down Expand Up @@ -1630,7 +1630,7 @@
}
}

private suspend fun receiveKexDhGexReply(msg: SshMsgKexDhGexReply) {
private fun receiveKexDhGexReply(msg: SshMsgKexDhGexReply) {
logger.info("Received DH_GEX_REPLY from server")
completeKex(
serverHostKey = msg.serverPublicHostKey().data(),
Expand Down Expand Up @@ -2321,13 +2321,13 @@
setRecipientChannel(recipientChannel.toLong())
_check()
}
writePacket(SshEnums.MessageType.SSH_MSG_CHANNEL_SUCCESS.id().toInt(), reply.toByteArray())
writePacket(SshEnums.MessageType.SSH_MSG_CHANNEL_SUCCESS.id().toInt(), reply.toByteArray(4))
} else {
val reply = SshMsgChannelFailure().apply {
setRecipientChannel(recipientChannel.toLong())
_check()
}
writePacket(SshEnums.MessageType.SSH_MSG_CHANNEL_FAILURE.id().toInt(), reply.toByteArray())
writePacket(SshEnums.MessageType.SSH_MSG_CHANNEL_FAILURE.id().toInt(), reply.toByteArray(4))
}
}

Expand Down Expand Up @@ -2426,11 +2426,7 @@

// Port forwarding support

internal suspend fun allocateChannelNumber(): Int {
channelNumberLock.withLock {
return nextLocalChannelNumber++
}
}
internal fun allocateChannelNumber(): Int = nextLocalChannelNumber.getAndIncrement()

internal suspend fun openDirectTcpipChannel(
host: String,
Expand Down Expand Up @@ -2882,7 +2878,7 @@
}

SshEnums.MessageType.SSH_MSG_SERVICE_ACCEPT -> {
val msg = parseBody(packet, ::SshMsgServiceAccept)
val msg = packet.body() as SshMsgServiceAccept
requireAccepted(stateMachine.receiveServiceAccept(msg.serviceName().value()), msgType)
}

Expand All @@ -2895,7 +2891,7 @@
}

SshEnums.MessageType.SSH_MSG_UNIMPLEMENTED -> {
logger.debug("Peer reported packet ${parseBody(packet, ::SshMsgUnimplemented).packetSequence()} as unimplemented")
logger.debug("Peer reported packet {} as unimplemented", (packet.body() as SshMsgUnimplemented).packetSequence())
}

SshEnums.MessageType.SSH_MSG_GLOBAL_REQUEST -> {
Expand Down Expand Up @@ -2993,14 +2989,14 @@
}

SshEnums.MessageType.SSH_MSG_DISCONNECT -> {
val msg = parseBody(packet, ::SshMsgDisconnect)
val msg = packet.body() as SshMsgDisconnect
logger.info("Received SSH_MSG_DISCONNECT from server: reason=${msg.reasonCode()}, description=${msg.description().value()}")
requireAccepted(stateMachine.disconnect(), msgType)
}

SshEnums.MessageType.SSH_MSG_EXT_INFO -> {
requireAccepted(stateMachine.authorizeExtInfo(), msgType)
processServerExtInfo(parseBody(packet, ::SshMsgExtInfo))
processServerExtInfo(packet.body() as SshMsgExtInfo)
}

SshEnums.MessageType.SSH_MSG_PING -> {
Expand All @@ -3010,7 +3006,7 @@
val pong = SshMsgPong()
pong.setData(createByteString(msg.data().data()))
pong._check()
writePacket(SshEnums.MessageType.SSH_MSG_PONG.id().toInt(), pong.toByteArray())
writePacket(SshEnums.MessageType.SSH_MSG_PONG.id().toInt(), pong.toByteArray(4L + pong.data().lenData()))
}
pongSend()
}
Expand Down Expand Up @@ -3163,7 +3159,7 @@
val ping = SshMsgPing()
ping.setData(createByteString(payload))
ping._check()
writePacket(SshEnums.MessageType.SSH_MSG_PING.id().toInt(), ping.toByteArray())
writePacket(SshEnums.MessageType.SSH_MSG_PING.id().toInt(), ping.toByteArray(4L + ping.data().lenData()))
}

internal suspend fun sendWindowAdjust(recipientChannel: Int, bytesToAdd: Int) {
Expand All @@ -3175,7 +3171,7 @@

writePacket(
SshEnums.MessageType.SSH_MSG_CHANNEL_WINDOW_ADJUST.id().toInt(),
msg.toByteArray(),
msg.toByteArray(8),
)
}

Expand All @@ -3187,7 +3183,7 @@

writePacket(
SshEnums.MessageType.SSH_MSG_CHANNEL_EOF.id().toInt(),
msg.toByteArray(),
msg.toByteArray(4),
)
}

Expand Down Expand Up @@ -3265,7 +3261,7 @@
}
writePacket(
SshEnums.MessageType.SSH_MSG_UNIMPLEMENTED.id().toInt(),
msg.toByteArray(),
msg.toByteArray(4),
)
}

Expand Down Expand Up @@ -3521,7 +3517,7 @@

writePacket(
SshEnums.MessageType.SSH_MSG_CHANNEL_CLOSE.id().toInt(),
msg.toByteArray(),
msg.toByteArray(4),
)
}

Expand All @@ -3541,7 +3537,7 @@

outboundPacketController.writePacket(
SshEnums.MessageType.SSH_MSG_PING.id().toInt(),
ping.toByteArray(),
ping.toByteArray(4L + ping.data().lenData()),
beforeWrite = {
pendingPings[seq] = current.copy(sentTimeNs = System.nanoTime())
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ import org.connectbot.sshlib.Timeouts
import org.connectbot.sshlib.client.asReadOnlyBuffer
import org.connectbot.sshlib.kaitaiParseFailureOrNull
import org.connectbot.sshlib.protocol.ByteString
import org.connectbot.sshlib.protocol.SftpAcceptedTransition
import org.connectbot.sshlib.protocol.SftpCopyData
import org.connectbot.sshlib.protocol.SftpState
import org.connectbot.sshlib.protocol.SftpStateMachine
Expand All @@ -47,7 +46,7 @@ import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.util.concurrent.atomic.AtomicBoolean

private typealias SftpTransition = suspend (suspend (SftpAcceptedTransition) -> Unit) -> Boolean
private typealias SftpTransition = suspend (() -> Unit) -> Boolean

/**
* Internal implementation of [SftpClient].
Expand All @@ -64,7 +63,6 @@ internal class SftpClientImpl private constructor(
private val requestTimeoutMs: Long,
) : SftpClient {

private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private val closed = AtomicBoolean()

override val isOpen: Boolean get() = !closed.get() && session.isOpen && stateMachine.state == SftpState.READY
Expand Down Expand Up @@ -384,7 +382,7 @@ internal class SftpClientImpl private constructor(
transition: SftpTransition = stateMachine::request,
timeoutMs: Long = requestTimeoutMs,
map: (SftpRawPacket) -> SftpResult<T>,
): SftpResult<T> = when (val result = dispatcher.request(type, payload, timeoutMs) { action -> transition { action() } }) {
): SftpResult<T> = when (val result = dispatcher.request(type, payload, timeoutMs, transition)) {
is SftpResult.Success -> try {
map(result.value)
} catch (e: SftpDecodeException) {
Expand Down Expand Up @@ -492,7 +490,7 @@ internal class SftpClientImpl private constructor(
// Send SSH_FXP_INIT
val initPayload = ByteBuffer.allocate(4)
initPayload.putInt(SFTP_VERSION)
val initResult = if (stateMachine.sendInit {}) {
val initResult = if (stateMachine.sendInit()) {
dispatcher.writeRaw(SSH_FXP_INIT, initPayload.array())
} else {
return SftpResult.ProtocolError("Failed to admit SFTP INIT")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,21 +66,21 @@ internal class SftpDispatcher(
}

/**
* Admit and write a request as one state-machine action, then await its response
* after the state-machine serialization point has been released.
* Register the response waiter inside the state-machine action. Queue the write
* and await its response after releasing the lifecycle lock.
*/
suspend fun request(
type: Int,
payload: ByteArray,
timeoutMs: Long = Timeouts.DEFAULT_SFTP_REQUEST_TIMEOUT_MS,
authorize: suspend (suspend () -> Unit) -> Boolean,
authorize: suspend (() -> Unit) -> Boolean,
): SftpResult<SftpRawPacket> = request(type, listOf(payload), timeoutMs, authorize)

suspend fun request(
type: Int,
payload: List<ByteArray>,
timeoutMs: Long = Timeouts.DEFAULT_SFTP_REQUEST_TIMEOUT_MS,
authorize: suspend (suspend () -> Unit) -> Boolean,
authorize: suspend (() -> Unit) -> Boolean,
): SftpResult<SftpRawPacket> {
var requestId = 0
var deferred: CompletableDeferred<SftpRawPacket>? = null
Expand Down Expand Up @@ -162,7 +162,7 @@ internal class SftpDispatcher(
suspend fun readRaw(): SftpResult<SftpRawPacket> {
val result = packetIO.readPacket()
if (result is SftpResult.Success && result.value.type == SSH_FXP_VERSION) {
stateMachine.receiveVersion { }
stateMachine.receiveVersion()
}
return result
}
Expand Down Expand Up @@ -209,11 +209,11 @@ internal class SftpDispatcher(

// Notify state machine directly of incoming packet
when (packet.type) {
SSH_FXP_STATUS -> stateMachine.receiveStatus { }
SSH_FXP_HANDLE -> stateMachine.receiveHandle { }
SSH_FXP_DATA -> stateMachine.receiveData { }
SSH_FXP_NAME -> stateMachine.receiveName { }
SSH_FXP_ATTRS -> stateMachine.receiveAttrs { }
SSH_FXP_STATUS -> stateMachine.receiveStatus()
SSH_FXP_HANDLE -> stateMachine.receiveHandle()
SSH_FXP_DATA -> stateMachine.receiveData()
SSH_FXP_NAME -> stateMachine.receiveName()
SSH_FXP_ATTRS -> stateMachine.receiveAttrs()
}

val header = SftpFrameHeader.ResponseHeader(ByteBufferKaitaiStream(responsePayload))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,42 +81,28 @@ internal class AesGcmCipher(
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec)
cipher.updateAAD(packetLength)
val output = ByteArray(plaintext.sumOf { it.size } + tagLength)
var written = 0
for (index in 0 until plaintext.lastIndex) {
val part = plaintext[index]
written += cipher.update(part, 0, part.size, output, written)
}
if (plaintext.isEmpty()) {
cipher.doFinal(output, written)
} else {
val last = plaintext.last()
cipher.doFinal(last, 0, last.size, output, written)
}
cipher.encryptParts(plaintext, output)
invocationCounter++
return output
}

override fun decrypt(packetLength: ByteArray, ciphertext: ByteArray, tag: ByteArray): ByteArray = decryptPacket(packetLength, ciphertext + tag)

override fun decryptPacket(packetLength: ByteArray, encrypted: ByteArray): ByteArray {
initDecrypt(packetLength, encrypted)
override fun decryptPacket(packetLength: ByteArray, encrypted: ByteArray, size: Int): ByteArray {
if (size !in tagLength..encrypted.size) throw TransportException("Truncated AEAD packet")
val gcmSpec = GCMParameterSpec(128, buildNonce())
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec)
cipher.updateAAD(packetLength)

try {
val plaintext = cipher.doFinal(encrypted)
val plaintext = cipher.doFinal(encrypted, 0, size)
invocationCounter++
return plaintext
} catch (e: AEADBadTagException) {
throw TransportException("AEAD authentication failed", e)
}
}

private fun initDecrypt(packetLength: ByteArray, encrypted: ByteArray) {
if (encrypted.size < tagLength) throw TransportException("Truncated AEAD packet")
val gcmSpec = GCMParameterSpec(128, buildNonce())
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec)
cipher.updateAAD(packetLength)
}

override fun destroy() {
key.fill(0)
iv.fill(0)
Expand Down
Loading
Loading