From e567071ad9e400a498971ed97e09811715ea4459 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 13:46:38 +0000 Subject: [PATCH] Android: SSH on libdmodemssh through JNI, sshj gone The SSH client is the same as iOS's and the GUI's now: native-ssh, on libssh, loaded as libdmodem_ssh_jni.so (NativeSsh.kt). SshLink polls it on its own thread; its channels carry the shell, commands, the port forwards (-L, -R, -D) and the forwarded agent's requests. Keys stay the app's: SSH's wire form (SshWire.kt), OpenSSH's and PEM keys read through the engine, PuTTY's .ppk read here, all on BouncyCastle. The engine: commands can forward the agent, a write tells what's still kept for the server (forwards hold back a fast sender), libssh built WITH_SERVER (its callbacks for the agent's channels need it), and its remote listen on port 0 patched to take the port from its own reply. The unit tests build the JNI library for the host (buildHostSsh) and run against it: OpenSSH's sshd, puttygen and Apache MINA's server. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRSV65geuGd6zMt2V6r --- app/build.gradle.kts | 29 +- app/lint.xml | 4 +- app/proguard-rules.pro | 9 +- app/src/main/cpp/CMakeLists.txt | 4 + .../java/org/dmodem/app/android/ssh/Agent.kt | 141 ++--- .../org/dmodem/app/android/ssh/Forwarding.kt | 272 +++++++--- .../java/org/dmodem/app/android/ssh/KeyGen.kt | 167 ++++-- .../java/org/dmodem/app/android/ssh/Keys.kt | 105 +--- .../org/dmodem/app/android/ssh/KnownHosts.kt | 59 +- .../org/dmodem/app/android/ssh/NativeSsh.kt | 123 +++++ .../java/org/dmodem/app/android/ssh/Ppk.kt | 180 ++++-- .../org/dmodem/app/android/ssh/Secrets.kt | 8 +- .../org/dmodem/app/android/ssh/SshLink.kt | 513 ++++++++++++------ .../org/dmodem/app/android/ssh/SshWire.kt | 195 +++++++ .../dmodem/app/android/terminal/Terminal.kt | 2 +- .../app/android/ssh/OpenSshInteropTest.kt | 2 +- .../org/dmodem/app/android/ssh/SshLinkTest.kt | 6 +- docs/building.md | 5 +- docs/features.md | 19 +- gradle/libs.versions.toml | 2 - ios/DModem/Sources/RemoteModel.swift | 2 +- native-ssh/CMakeLists.txt | 21 + native-ssh/cmake/BundledLibssh.cmake | 5 +- native-ssh/cmake/PatchLibssh.cmake | 49 ++ native-ssh/include/dmodemssh.h | 9 +- native-ssh/jni/ssh_jni.c | 289 ++++++++++ native-ssh/src/dmodemssh.c | 63 ++- native-ssh/test/dmodemssh_test.c | 9 +- 28 files changed, 1726 insertions(+), 566 deletions(-) create mode 100644 app/src/main/java/org/dmodem/app/android/ssh/NativeSsh.kt create mode 100644 app/src/main/java/org/dmodem/app/android/ssh/SshWire.kt create mode 100644 native-ssh/cmake/PatchLibssh.cmake create mode 100644 native-ssh/jni/ssh_jni.c diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 4837e03..7aa3d7a 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -59,8 +59,8 @@ android { } externalNativeBuild { cmake { - // only the app's libraries (the modem's, the local shell's ptys): not dmodemd or D-Modem's other programs - targets += listOf("dmodem_jni", "dmodem_pty") + // only the app's libraries (the modem's, the local shell's ptys, the SSH client's): not dmodemd or D-Modem's other programs + targets += listOf("dmodem_jni", "dmodem_pty", "dmodem_ssh_jni") arguments += listOf("-DANDROID_STL=c++_static") // (a special build's name for the native code too: "led-probe" probes the Agere's LEDs) providers.gradleProperty("dmodem.special").orNull?.let { arguments += "-DDMODEM_SPECIAL=$it" } @@ -134,7 +134,7 @@ android { packaging { resources { - // (sshj's dependencies each carry these: one is enough, the licences are in the app's) + // (dependencies each carry these: one is enough, the licences are in the app's) excludes += setOf("META-INF/LICENSE.md", "META-INF/NOTICE.md", "META-INF/LICENSE-notice.md", "META-INF/versions/9/OSGI-INF/MANIFEST.MF") pickFirsts += setOf("META-INF/INDEX.LIST") } @@ -162,12 +162,11 @@ dependencies { implementation(libs.androidx.lifecycle.runtime.compose) implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.datastore.preferences) - // SSH: sshj on BouncyCastle (Android's own "BC" is cut down: the full one is registered at start) - implementation(libs.sshj) // the Linux systems' root file systems (.tar.xz) implementation(libs.xz) + // SSH keys made, read and used for the agent: BouncyCastle (Android's own "BC" is cut down: + // the full one is registered at start); the SSH client itself is native-ssh, on libssh implementation(libs.bcprov) - implementation(libs.bcpkix) implementation(platform(libs.compose.bom)) implementation(libs.compose.ui) implementation(libs.compose.ui.tooling.preview) @@ -180,6 +179,7 @@ dependencies { testImplementation(libs.androidx.test.core) // an SSH server for the SSH client's tests testImplementation(libs.mina.sshd.core) + testImplementation(libs.bcpkix) testImplementation(platform(libs.compose.bom)) testImplementation(libs.compose.ui.test.junit4) debugImplementation(libs.compose.ui.test.manifest) @@ -187,11 +187,28 @@ dependencies { androidTestImplementation(libs.androidx.test.ext.junit) } +// native-ssh's JNI library for this machine, for the JVM's unit tests (cmake, a C compiler and a JDK's headers) +val hostSshDir = layout.buildDirectory.dir("host-ssh") +val buildHostSsh = tasks.register("buildHostSsh") { + description = "Builds native-ssh's JNI library for the build host, for the unit tests" + inputs.dir(rootProject.file("native-ssh")) + outputs.file(hostSshDir.map { it.file(System.mapLibraryName("dmodem_ssh_jni")) }) + val dir = hostSshDir.get().asFile.path + commandLine( + "sh", "-c", + "cmake -S \"$1\" -B \"$2\" -DDMODEM_SSH_JNI=ON -DCMAKE_BUILD_TYPE=Release && cmake --build \"$2\" --target dmodem_ssh_jni -j4", + "sh", rootProject.file("native-ssh").path, dir, + ) +} + // Robolectric fetches its Android framework jars itself: -ProbolectricRepoUrl= to fetch them elsewhere tasks.withType().configureEach { providers.gradleProperty("robolectricRepoUrl").orNull?.let { systemProperty("robolectric.dependency.repo.url", it) } + // the SSH client's JNI library built for the host (native-ssh), for the SSH tests + dependsOn(buildHostSsh) + systemProperty("java.library.path", hostSshDir.get().asFile.path) // each test named as it starts in CI's log, so a test that hangs is the last one started if (System.getenv("CI") != null) testLogging { events("started", "failed", "skipped") } } diff --git a/app/lint.xml b/app/lint.xml index 3995799..b73c002 100644 --- a/app/lint.xml +++ b/app/lint.xml @@ -1,7 +1,7 @@ - + diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index d7ca049..acfab31 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -7,10 +7,11 @@ static void onExit(int); } -# SSH: sshj and BouncyCastle find their algorithms by name (JCA providers, -# factories) at run time: keep them whole. --keep class net.schmizz.sshj.** { *; } --keep class com.hierynomus.sshj.** { *; } +# SSH: libdmodem_ssh_jni's JNI functions are named after NativeSsh's natives +-keep class org.dmodem.app.android.ssh.NativeSsh { native ; } + +# BouncyCastle finds its algorithms by name (JCA providers, factories) at +# run time: keep them whole. -keep class org.bouncycastle.jcajce.provider.** { *; } -keep class org.bouncycastle.jce.provider.** { *; } -keep class org.bouncycastle.pqc.jcajce.provider.** { *; } diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index ff5d1f2..9b005bd 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -90,4 +90,8 @@ if(ANDROID) add_library(dmodem_pty SHARED pty.c) target_compile_options(dmodem_pty PRIVATE -Wall -Wextra) target_link_options(dmodem_pty PRIVATE -Wl,-z,max-page-size=16384) + + # the SSH client (NativeSsh.kt): libdmodemssh on libssh and its own + # Mbed TLS, libdmodem_ssh_jni.so (native-ssh, the GUI's and iOS's too) + add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../../../../native-ssh native-ssh) endif() diff --git a/app/src/main/java/org/dmodem/app/android/ssh/Agent.kt b/app/src/main/java/org/dmodem/app/android/ssh/Agent.kt index 5f42f73..dc3c6e5 100644 --- a/app/src/main/java/org/dmodem/app/android/ssh/Agent.kt +++ b/app/src/main/java/org/dmodem/app/android/ssh/Agent.kt @@ -2,22 +2,16 @@ // Copyright (C) 2026 Neo-Desktop package org.dmodem.app.android.ssh -import net.schmizz.sshj.DefaultConfig -import net.schmizz.sshj.common.Buffer -import net.schmizz.sshj.common.SSHPacket -import net.schmizz.sshj.connection.Connection -import net.schmizz.sshj.connection.channel.direct.SessionChannel -import net.schmizz.sshj.connection.channel.forwarded.AbstractForwardedChannel -import net.schmizz.sshj.connection.channel.forwarded.AbstractForwardedChannelOpener -import net.schmizz.sshj.connection.channel.forwarded.ConnectListener -import net.schmizz.sshj.signature.Signature +import java.io.ByteArrayOutputStream import java.io.DataInputStream import java.io.EOFException import java.io.IOException import java.io.InputStream import java.io.OutputStream +import java.math.BigInteger import java.security.KeyPair -import java.util.concurrent.TimeUnit +import java.security.Signature +import java.security.interfaces.ECPublicKey /** * An agent's keys: those the server (and the hosts reached from it) may @@ -46,9 +40,7 @@ class AgentServer(private val keys: AgentKeys, private val owner: Any = Unit, pr val len = d.readInt() if (len <= 0 || len > MAX_MESSAGE) return val msg = ByteArray(len).also { d.readFully(it) } - val reply = handle(Buffer.PlainBuffer(msg)) - o.write(Buffer.PlainBuffer().putUInt32(reply.size.toLong()).compactData) - o.write(reply) + o.write(frame(handle(SshReader(msg)))) o.flush() } } catch (_: EOFException) { @@ -56,11 +48,34 @@ class AgentServer(private val keys: AgentKeys, private val owner: Any = Unit, pr } } + /** + * bytes from an agent channel: each whole request in them answered, the + * replies (length-prefixed) to send back; a part of one kept for the + * next; null when a request is too long (the channel to close) + */ + fun feed(data: ByteArray): ByteArray? { + pending.write(data) + val out = ByteArrayOutputStream() + var buf = pending.toByteArray() + while (buf.size >= 4) { + val len = SshReader(buf).int() + if (len <= 0 || len > MAX_MESSAGE) return null + if (buf.size < 4 + len) break + out.write(frame(handle(SshReader(buf.copyOfRange(4, 4 + len))))) + buf = buf.copyOfRange(4 + len, buf.size) + } + pending.reset() + pending.write(buf) + return out.toByteArray() + } + + private val pending = ByteArrayOutputStream() + /** one request's reply */ - fun handle(b: Buffer.PlainBuffer): ByteArray = try { - when (b.readByte().toInt()) { + fun handle(b: SshReader): ByteArray = try { + when (b.byte()) { REQUEST_IDENTITIES -> identities() - SIGN_REQUEST -> sign(b.readBytes(), b.readBytes(), if (b.available() >= 4) b.readUInt32AsInt() else 0) + SIGN_REQUEST -> sign(b.bytes(), b.bytes(), if (b.available() >= 4) b.int() else 0) else -> FAILURE } } catch (e: Exception) { @@ -71,9 +86,9 @@ class AgentServer(private val keys: AgentKeys, private val owner: Any = Unit, pr /** the keys' list: each key's blob and name */ private fun identities(): ByteArray { val ks = keys.list() - val r = Buffer.PlainBuffer().putByte(IDENTITIES_ANSWER.toByte()).putUInt32(ks.size.toLong()) - for ((name, kp) in ks) r.putBytes(KeyFormat.blob(kp.public)).putString(name) - return r.compactData + val r = SshWriter().byte(IDENTITIES_ANSWER).uint32(ks.size.toLong()) + for ((name, kp) in ks) r.bytes(KeyFormat.blob(kp.public)).string(name) + return r.bytes() } /** [data] signed with the key whose blob is [blob] (RSA's hash as [flags] ask), once confirmed: the response, or FAILURE */ @@ -91,22 +106,54 @@ class AgentServer(private val keys: AgentKeys, private val owner: Any = Unit, pr flags and RSA_SHA2_256 != 0 -> "rsa-sha2-256" else -> "ssh-rsa" } - val sig = signature(alg) - sig.initSign(kp.private) - sig.update(data) - val encoded = sig.encode(sig.sign()) + val encoded = signature(alg, kp, data) log("agent: signed with $name ($alg)") - val inner = Buffer.PlainBuffer().putString(alg).putBytes(encoded).compactData - return Buffer.PlainBuffer().putByte(SIGN_RESPONSE.toByte()).putBytes(inner).compactData + val inner = SshWriter().string(alg).bytes(encoded).bytes() + return SshWriter().byte(SIGN_RESPONSE).bytes(inner).bytes() } - /** a signature of algorithm [alg], from sshj's key algorithms */ - private fun signature(alg: String): Signature { - val f = DefaultConfig().keyAlgorithms.firstOrNull { it.name == alg } ?: throw IOException("no $alg signatures") - return f.create().newSignature() + /** [data] signed by [kp] as SSH's [alg] has it: Ed25519's 64 bytes, RSA's PKCS#1, ECDSA's r and s as mpints */ + private fun signature(alg: String, kp: KeyPair, data: ByteArray): ByteArray { + SshSecurity.ensure() + val jca = when (alg) { + "ssh-ed25519" -> "Ed25519" + "ssh-rsa" -> "SHA1withRSA" + "rsa-sha2-256" -> "SHA256withRSA" + "rsa-sha2-512" -> "SHA512withRSA" + else -> when ((kp.public as? ECPublicKey)?.params?.curve?.field?.fieldSize) { + 256 -> "SHA256withECDSA" + 384 -> "SHA384withECDSA" + 521 -> "SHA512withECDSA" + else -> throw IOException("no $alg signatures") + } + } + val sig = (if (jca == "Ed25519") Signature.getInstance(jca, "BC") else Signature.getInstance(jca)).run { + initSign(kp.private) + update(data) + sign() + } + if (kp.public !is ECPublicKey) return sig + // (DER's SEQUENCE of two INTEGERs, as SSH's two mpints) + val r = SshReader(sig) + /** a DER length */ + fun len(): Int { + val b = r.byte() + return if (b < 0x80) b else (0 until (b and 0x7f)).fold(0) { v, _ -> (v shl 8) or r.byte() } + } + /** a DER INTEGER */ + fun integer(): BigInteger { + if (r.byte() != 0x02) throw IOException("not an ECDSA signature") + return BigInteger(r.raw(len())) + } + if (r.byte() != 0x30) throw IOException("not an ECDSA signature") + len() + return SshWriter().mpint(integer()).mpint(integer()).bytes() } companion object { + /** [msg] with its length before it */ + fun frame(msg: ByteArray): ByteArray = SshWriter().bytes(msg).bytes() + const val FAILURE_CODE = 5 const val REQUEST_IDENTITIES = 11 const val IDENTITIES_ANSWER = 12 @@ -118,39 +165,3 @@ class AgentServer(private val keys: AgentKeys, private val owner: Any = Unit, pr private val FAILURE = byteArrayOf(FAILURE_CODE.toByte()) } } - -/** A session that can ask for the agent to be forwarded (sshj has no call for it). */ -class AgentSession(conn: Connection) : SessionChannel(conn) { - /** "auth-agent-req@openssh.com": the server to open agent channels back to us; false if it won't */ - fun requestAgentForwarding(): Boolean = try { - sendChannelRequest("auth-agent-req@openssh.com", true, Buffer.PlainBuffer()) - .await(conn.timeoutMs.toLong(), TimeUnit.MILLISECONDS) - true - } catch (_: IOException) { - false - } -} - -/** The agent channels the server opens, each served by an [AgentServer]. */ -class AgentForwarder(conn: Connection, private val server: AgentServer) : - AbstractForwardedChannelOpener(TYPE, conn) { - - private class AgentChannel(conn: Connection, recipient: Int, window: Long, maxPacket: Long) : - AbstractForwardedChannel(conn, TYPE, recipient, window, maxPacket, "", 0) - - /** the server's agent channel opened: confirmed and served, on the listener's thread */ - override fun handleOpen(buf: SSHPacket) { - val ch = AgentChannel(conn, buf.readUInt32AsInt(), buf.readUInt32(), buf.readUInt32()) - callListener( - ConnectListener { c -> - c.confirm() - c.use { server.serve(it.inputStream, it.outputStream) } - }, - ch, - ) - } - - companion object { - const val TYPE = "auth-agent@openssh.com" - } -} diff --git a/app/src/main/java/org/dmodem/app/android/ssh/Forwarding.kt b/app/src/main/java/org/dmodem/app/android/ssh/Forwarding.kt index 46ad25d..8058592 100644 --- a/app/src/main/java/org/dmodem/app/android/ssh/Forwarding.kt +++ b/app/src/main/java/org/dmodem/app/android/ssh/Forwarding.kt @@ -6,10 +6,6 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update -import net.schmizz.sshj.SSHClient -import net.schmizz.sshj.connection.channel.Channel -import net.schmizz.sshj.connection.channel.forwarded.ConnectListener -import net.schmizz.sshj.connection.channel.forwarded.RemotePortForwarder import java.io.Closeable import java.io.IOException import java.io.InputStream @@ -123,6 +119,138 @@ data class ForwardState( val total: Int = 0, ) +/** A channel's events, from its connection's thread (each to return quickly). */ +interface ChannelHandler { + /** opened, or refused ([why]) */ + fun opened(ok: Boolean, why: String?) {} + + /** its data ([stderr]: the command's error output) */ + fun data(b: ByteArray, stderr: Boolean) {} + + /** its end of data */ + fun eof() {} + + /** its command's exit status */ + fun exit(status: Int) {} + + /** closed: its last event */ + fun closed() {} +} + +/** What forwards need of a connection: its channels, each told to its handler. */ +interface SshChannels { + /** a TCP connection from the server to host:port, for one from [from]:[fromPort], told to [x]: its channel, or -1 */ + fun direct(host: String, port: Int, from: String, fromPort: Int, x: ChannelHandler): Int + + /** the server asked to listen ([address] null: its default): [done] told the port bound, or -1 and why; false if it can't be asked */ + fun listen(address: String?, port: Int, done: (Int, String?) -> Unit): Boolean + + /** that listen stopped */ + fun unlisten(address: String?, port: Int) + + /** data to [x]'s channel: the bytes still waiting for the server, or -1 if it's gone */ + fun write(channel: Int, x: ChannelHandler, data: ByteArray, offset: Int, length: Int): Int + + /** [x]'s channel's end of data sent */ + fun eof(channel: Int, x: ChannelHandler) + + /** [x]'s channel closed */ + fun close(channel: Int, x: ChannelHandler) +} + +/** + * A socket and a channel spliced, both ways: the channel's data written to + * the socket by a thread of its own (queued until [start]), the socket's + * read to the channel by another (held back while the server's window is + * full); each one's end passed on as the other's. [done] once the channel + * has closed. + */ +class Splice(private val link: SshChannels) : ChannelHandler { + @Volatile var channel = -1 + @Volatile private var socket: Socket? = null + private val queue = java.util.concurrent.LinkedBlockingQueue() + /** whether the channel opened, once it's known */ + val open = java.util.concurrent.CompletableFuture() + /** the channel closed */ + val done = java.util.concurrent.CountDownLatch(1) + + /** opened: the socket started, if there's one ([start] does it when it comes) */ + override fun opened(ok: Boolean, why: String?) { + open.complete(ok) + } + + /** the channel's data, queued for the socket */ + override fun data(b: ByteArray, stderr: Boolean) { + queue.put(b) + } + + /** the channel's end, the socket's output shut once what's queued is written */ + override fun eof() { + queue.put(END) + } + + /** the channel gone: the socket closed */ + override fun closed() { + open.complete(false) + queue.put(END) + runCatching { socket?.close() } + done.countDown() + } + + /** [s] spliced to the channel: both ways, each on a thread of its own */ + fun start(s: Socket) { + socket = s + if (done.count == 0L) { + runCatching { s.close() } + return + } + Forwards.thread("splice-down") { + try { + val o = s.getOutputStream() + while (true) { + val b = queue.take() + if (b === END) break + o.write(b) + o.flush() + } + runCatching { s.shutdownOutput() } + } catch (_: Exception) { + link.close(channel, this) + } + } + Forwards.thread("splice-up") { + val buf = ByteArray(32 * 1024) + try { + val i = s.getInputStream() + while (true) { + val n = i.read(buf) + if (n < 0) break + var waiting = link.write(channel, this, buf, 0, n) + // (the server's window full: held back until it takes more) + while (waiting > HIGH_WATER) { + Thread.sleep(5) + waiting = link.write(channel, this, buf, 0, 0) + } + if (waiting < 0) break + } + link.eof(channel, this) + } catch (_: Exception) { + link.close(channel, this) + } + } + } + + /** until the channel has closed (or [ms] have passed) */ + fun await(ms: Long = Long.MAX_VALUE) { + done.await(ms, java.util.concurrent.TimeUnit.MILLISECONDS) + } + + companion object { + private val END = ByteArray(0) + private const val HIGH_WATER = 256 * 1024 + } +} + /** * An SSH connection's port forwards: local (a socket here, each connection * a direct-tcpip channel to host:hostport from the server), remote (the @@ -130,7 +258,7 @@ data class ForwardState( * (a SOCKS 4/4a/5 proxy here, each connection to where its client asks). */ class Forwards( - private val client: SSHClient, + private val link: SshChannels, private val _states: MutableStateFlow> = MutableStateFlow(emptyList()), private val log: (String) -> Unit = {}, ) : Closeable { @@ -138,6 +266,8 @@ class Forwards( val states: StateFlow> = _states.asStateFlow() private val running = HashMap() + /** the remote forwards by the port the server bound */ + private val remotes = java.util.concurrent.ConcurrentHashMap() @Volatile private var closed = false @@ -157,13 +287,17 @@ class Forwards( } true } catch (e: Exception) { - val why = e.message ?: e.javaClass.simpleName - set(spec) { it.copy(listening = false, error = why) } - log("forward ${spec}: $why") + failed(spec, e.message ?: e.javaClass.simpleName) false } } + /** [spec] not listening, for [why] */ + private fun failed(spec: ForwardSpec, why: String) { + set(spec) { it.copy(listening = false, error = why) } + log("forward ${spec}: $why") + } + /** a forward stopped and gone from [states] */ @Synchronized fun stop(spec: ForwardSpec) { @@ -200,53 +334,92 @@ class Forwards( return server } + /** a channel from the server to [host]:[port] for [s], once it's open (null if it's refused) */ + private fun open(host: String, port: Int, s: Socket): Splice? { + val sp = Splice(link) + sp.channel = link.direct(host, port, s.inetAddress.hostAddress ?: "127.0.0.1", s.port, sp) + if (sp.channel < 0) return null + val ok = try { + sp.open.get(30, java.util.concurrent.TimeUnit.SECONDS) + } catch (_: Exception) { + false + } + if (!ok) { + link.close(sp.channel, sp) + log("forward to $host:$port: refused by the server") + return null + } + return sp + } + /** a connection to a local or SOCKS forward: its channel from the server (SOCKS's to where its client asks), spliced to it, counted while open */ private fun serve(spec: ForwardSpec, s: Socket) { counted(spec) { s.use { s.tcpNoDelay = true - val ch: Channel = try { + val sp = try { if (spec.type == ForwardSpec.Type.DYNAMIC) { - Socks.handshake(s.getInputStream(), s.getOutputStream()) { h, p -> - try { - client.newDirectConnection(h, p) - } catch (e: IOException) { - log("SOCKS to $h:$p: ${e.message}") - null - } - } ?: return@counted + Socks.handshake(s.getInputStream(), s.getOutputStream()) { h, p -> open(h, p, s) } } else { - client.newDirectConnection(spec.host, spec.hostPort) + open(spec.host, spec.hostPort, s) } } catch (e: IOException) { log("forward to ${spec.host}:${spec.hostPort}: ${e.message}") - return@counted - } - ch.use { splice(s, it) } + null + } ?: return@counted + sp.start(s) + sp.await() } } } /** the server asked to listen for a remote forward, each connection to host:hostport from here: its cancel */ private fun remote(spec: ForwardSpec): Closeable { - val rpf = client.remotePortForwarder - val listener = ConnectListener { ch -> - // (in a thread sshj starts for the channel; refused if this throws) - val s = Socket() - try { - s.connect(InetSocketAddress(spec.host, spec.hostPort), 10_000) - s.tcpNoDelay = true - } catch (e: IOException) { - runCatching { s.close() } - log("forward from the server to ${spec.host}:${spec.hostPort}: ${e.message}") - throw e + var bound = -1 + val asked = link.listen(spec.bind, spec.port) { port, why -> + if (port < 0) { + failed(spec, why ?: "the server refused to listen") + } else { + bound = port + remotes[port] = spec + set(spec) { it.copy(listening = true, error = null, boundPort = port) } } - ch.confirm() - counted(spec) { s.use { ch.use { splice(s, ch) } } } } - val bound = rpf.bind(RemotePortForwarder.Forward(spec.bind ?: "", spec.port), listener) - set(spec) { it.copy(listening = true, error = null, boundPort = bound.port) } - return Closeable { runCatching { rpf.cancel(bound) } } + if (!asked) throw IOException("not connected") + return Closeable { + if (bound >= 0) { + remotes.remove(bound) + link.unlisten(spec.bind, bound) + } + } + } + + /** + * a connection the server took on a remote forward's [port] (on the + * connection's thread): its handler, the socket to host:hostport made + * on a thread of its own; null if it isn't one of ours + */ + fun incoming(channel: Int, port: Int): ChannelHandler? { + val spec = remotes[port] ?: return null + val sp = Splice(link) + sp.channel = channel + thread("fwd-R$port") { + counted(spec) { + val s = Socket() + try { + s.connect(InetSocketAddress(spec.host, spec.hostPort), 10_000) + s.tcpNoDelay = true + } catch (e: IOException) { + runCatching { s.close() } + log("forward from the server to ${spec.host}:${spec.hostPort}: ${e.message}") + link.close(channel, sp) + return@counted + } + sp.start(s) + sp.await() + } + } + return sp } /** [body] run as one of [spec]'s connections: counted open while it runs, and in the total */ @@ -262,31 +435,6 @@ class Forwards( companion object { /** [body] run on a daemon thread named [name] */ fun thread(name: String, body: () -> Unit) = Thread(body, name).apply { isDaemon = true }.start() - - /** both ways between a socket and a channel, until either ends */ - fun splice(s: Socket, ch: Channel) { - val up = Thread({ - copy(s.getInputStream(), ch.outputStream) - runCatching { ch.outputStream.close() } - }, "splice-up").apply { isDaemon = true; start() } - copy(ch.inputStream, s.getOutputStream()) - runCatching { s.shutdownOutput() } - up.join(30_000) - } - - /** [i] copied to [o] until it ends (or fails) */ - private fun copy(i: InputStream, o: OutputStream) { - val buf = ByteArray(32 * 1024) - try { - while (true) { - val n = i.read(buf) - if (n < 0) break - o.write(buf, 0, n) - o.flush() - } - } catch (_: IOException) { - } - } } } diff --git a/app/src/main/java/org/dmodem/app/android/ssh/KeyGen.kt b/app/src/main/java/org/dmodem/app/android/ssh/KeyGen.kt index 4f46cea..8a70b51 100644 --- a/app/src/main/java/org/dmodem/app/android/ssh/KeyGen.kt +++ b/app/src/main/java/org/dmodem/app/android/ssh/KeyGen.kt @@ -2,11 +2,13 @@ // Copyright (C) 2026 Neo-Desktop package org.dmodem.app.android.ssh -import com.hierynomus.sshj.userauth.keyprovider.bcrypt.BCrypt -import net.schmizz.sshj.common.Buffer import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters import org.bouncycastle.crypto.util.PrivateKeyFactory +import java.io.IOException +import java.math.BigInteger +import java.security.KeyFactory import java.security.KeyPair +import java.security.PrivateKey import java.security.MessageDigest import java.security.PublicKey import java.security.SecureRandom @@ -14,10 +16,10 @@ import java.security.interfaces.ECPrivateKey import java.security.interfaces.ECPublicKey import java.security.interfaces.RSAPrivateCrtKey import java.security.interfaces.RSAPublicKey +import java.security.spec.ECPrivateKeySpec +import java.security.spec.PKCS8EncodedKeySpec +import java.security.spec.RSAPrivateCrtKeySpec import java.util.Base64 -import javax.crypto.Cipher -import javax.crypto.spec.IvParameterSpec -import javax.crypto.spec.SecretKeySpec /** * What ssh-keygen tells of a key and writes of it: its size, its @@ -94,73 +96,130 @@ object KeyGen { /** * The private key as "-----BEGIN OPENSSH PRIVATE KEY-----", for ssh and * ssh-keygen (and this app's import); encrypted with [passphrase] when - * it isn't empty. + * it isn't empty, as ssh-keygen does it (by libdmodemssh: bcrypt KDF, + * aes256-ctr). */ - fun openSshPrivate(kp: KeyPair, comment: String, passphrase: String = "", rounds: Int = 16): String { - val pub = KeyFormat.blob(kp.public) - val encrypted = passphrase.isNotEmpty() - val block = if (encrypted) 16 else 8 - val check = SecureRandom().nextInt().toLong() and 0xffffffffL - val priv = Buffer.PlainBuffer().putUInt32(check).putUInt32(check) - privateFields(kp, priv) - priv.putString(comment) - var pad = 1 - while (priv.available() % block != 0) priv.putByte((pad++).toByte()) - var secret = priv.compactData + fun openSshPrivate(kp: KeyPair, comment: String, passphrase: String = ""): String { + val plain = openSshPlain(kp, comment) + if (passphrase.isEmpty()) return plain + return NativeSsh.keyExport(plain, null, passphrase) ?: throw IOException("the key couldn't be encrypted") + } - val kdfOptions: ByteArray - if (encrypted) { - val salt = ByteArray(16).also { SecureRandom().nextBytes(it) } - kdfOptions = Buffer.PlainBuffer().putBytes(salt).putUInt32(rounds.toLong()).compactData - val keyIv = ByteArray(48) - BCrypt().pbkdf(passphrase.toByteArray(), salt, rounds, keyIv) - val c = Cipher.getInstance("AES/CTR/NoPadding") - c.init(Cipher.ENCRYPT_MODE, SecretKeySpec(keyIv.copyOfRange(0, 32), "AES"), IvParameterSpec(keyIv.copyOfRange(32, 48))) - secret = c.doFinal(secret) - } else { - kdfOptions = ByteArray(0) - } - val out = Buffer.PlainBuffer() - out.putRawBytes("openssh-key-v1\u0000".toByteArray()) - out.putString(if (encrypted) "aes256-ctr" else "none") - out.putString(if (encrypted) "bcrypt" else "none") - out.putBytes(kdfOptions) - out.putUInt32(1) - out.putBytes(pub) - out.putBytes(secret) - val b64 = Base64.getEncoder().encodeToString(out.compactData).chunked(70).joinToString("\n") + /** the private key in OpenSSH's form, unencrypted */ + private fun openSshPlain(kp: KeyPair, comment: String): String { + val check = SecureRandom().nextInt().toLong() and 0xffffffffL + val priv = SshWriter().uint32(check).uint32(check) + privateFields(kp, priv) + priv.string(comment) + var pad = 1 + while (priv.size() % 8 != 0) priv.byte(pad++) + val out = SshWriter() + .raw("openssh-key-v1\u0000".toByteArray()) + .string("none").string("none").bytes(ByteArray(0)) + .uint32(1) + .bytes(KeyFormat.blob(kp.public)) + .bytes(priv.bytes()) + val b64 = Base64.getEncoder().encodeToString(out.bytes()).chunked(70).joinToString("\n") return "-----BEGIN OPENSSH PRIVATE KEY-----\n$b64\n-----END OPENSSH PRIVATE KEY-----\n" } /** the key's type and private fields into [b], as OpenSSH's private key section has them (RSA, ECDSA or Ed25519) */ - private fun privateFields(kp: KeyPair, b: Buffer.PlainBuffer) { - val type = KeyFormat.type(kp.public) - b.putString(type) + private fun privateFields(kp: KeyPair, b: SshWriter) { + b.string(KeyFormat.type(kp.public)) when (val p = kp.private) { is RSAPrivateCrtKey -> { - b.putMPInt(p.modulus).putMPInt(p.publicExponent).putMPInt(p.privateExponent) - b.putMPInt(p.crtCoefficient).putMPInt(p.primeP).putMPInt(p.primeQ) + b.mpint(p.modulus).mpint(p.publicExponent).mpint(p.privateExponent) + b.mpint(p.crtCoefficient).mpint(p.primeP).mpint(p.primeQ) } is ECPrivateKey -> { // the curve's name and the public point, as in the public blob; then d - val pubBlob = Buffer.PlainBuffer(KeyFormat.blob(kp.public)) - pubBlob.readString() - b.putString(pubBlob.readString()) - b.putBytes(pubBlob.readBytes()) - b.putMPInt(p.s) + val pub = kp.public as ECPublicKey + b.string(KeyFormat.curve(pub.params.curve.field.fieldSize).first) + b.bytes(KeyFormat.point(pub)) + b.mpint(p.s) } else -> { // Ed25519: the 32-byte public key, then seed and public key together - val seed = (PrivateKeyFactory.createKey(p.encoded) as Ed25519PrivateKeyParameters).encoded - val pubBlob = Buffer.PlainBuffer(KeyFormat.blob(kp.public)) - pubBlob.readString() - val pk = pubBlob.readBytes() - b.putBytes(pk) - b.putBytes(seed + pk) + val pk = KeyFormat.ed25519(kp.public) + b.bytes(pk) + b.bytes(ed25519Seed(p) + pk) } } } + /** an Ed25519 private key's 32-byte seed */ + fun ed25519Seed(k: PrivateKey): ByteArray = + (PrivateKeyFactory.createKey(k.encoded) as Ed25519PrivateKeyParameters).encoded + + /** an Ed25519 private key from its 32-byte seed */ + fun ed25519Private(seed: ByteArray): PrivateKey { + if (seed.size != 32) throw IOException("an Ed25519 seed is 32 bytes") + SshSecurity.ensure() + return KeyFactory.getInstance("Ed25519", "BC").generatePrivate(PKCS8EncodedKeySpec(ED25519_PKCS8 + seed)) + } + + /** PKCS#8's prefix of an Ed25519 key, before its seed */ + private val ED25519_PKCS8 = byteArrayOf( + 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20, + ) + + /** an RSA private key made whole from n, e, d and its primes */ + fun rsaPrivate(n: BigInteger, e: BigInteger, d: BigInteger, p: BigInteger, q: BigInteger): PrivateKey { + val one = BigInteger.ONE + return KeyFactory.getInstance("RSA").generatePrivate( + RSAPrivateCrtKeySpec(n, e, d, p, q, d.mod(p.subtract(one)), d.mod(q.subtract(one)), q.modInverse(p)), + ) + } + + /** an ECDSA private key: d on the curve of the SSH name [curveName] */ + fun ecPrivate(curveName: String, d: BigInteger): PrivateKey { + val bits = when (curveName) { + "nistp256" -> 256 + "nistp384" -> 384 + "nistp521" -> 521 + else -> throw IOException("unknown curve $curveName") + } + return KeyFactory.getInstance("EC").generatePrivate(ECPrivateKeySpec(d, KeyFormat.ecParams(KeyFormat.curve(bits).second))) + } + + /** + * An unencrypted OpenSSH private key ("BEGIN OPENSSH PRIVATE KEY") read: + * its pair and its comment. An encrypted one is opened first by + * [NativeSsh.keyExport]. + */ + fun readOpenSsh(text: String): Pair { + val body = text.substringAfter("-----BEGIN OPENSSH PRIVATE KEY-----").substringBefore("-----END") + val r = SshReader(Base64.getMimeDecoder().decode(body.trim())) + if (!r.raw(15).contentEquals("openssh-key-v1\u0000".toByteArray())) throw IOException("not an OpenSSH key") + if (r.string() != "none" || r.string() != "none") throw IOException("the key is encrypted") + r.bytes() // the KDF's options + if (r.int() != 1) throw IOException("one key per file only") + val pub = KeyFormat.fromBlob(r.bytes()) + val p = SshReader(r.bytes()) + if (p.uint32() != p.uint32()) throw IOException("the key's check numbers differ") + val type = p.string() + val priv: PrivateKey = when { + type == "ssh-rsa" -> { + val n = p.mpint() + val e = p.mpint() + val d = p.mpint() + p.mpint() // iqmp + rsaPrivate(n, e, d, p.mpint(), p.mpint()) + } + type.startsWith("ecdsa-sha2-") -> { + val curve = p.string() + p.bytes() // the public point + ecPrivate(curve, p.mpint()) + } + type == "ssh-ed25519" -> { + p.bytes() // the public key + ed25519Private(p.bytes().copyOf(32)) + } + else -> throw IOException("unknown key type $type") + } + return KeyPair(pub, priv) to p.string() + } + /** the command that adds [publicKey] to the server's authorized_keys once (ssh-copy-id) */ fun copyIdCommand(publicKey: String): String { val k = publicKey.trim().replace("'", "") diff --git a/app/src/main/java/org/dmodem/app/android/ssh/Keys.kt b/app/src/main/java/org/dmodem/app/android/ssh/Keys.kt index c9a100b..676bd18 100644 --- a/app/src/main/java/org/dmodem/app/android/ssh/Keys.kt +++ b/app/src/main/java/org/dmodem/app/android/ssh/Keys.kt @@ -5,24 +5,12 @@ package org.dmodem.app.android.ssh import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow -import net.schmizz.sshj.common.Buffer -import net.schmizz.sshj.common.KeyType -import net.schmizz.sshj.userauth.keyprovider.KeyPairWrapper -import net.schmizz.sshj.userauth.keyprovider.KeyProvider -import net.schmizz.sshj.userauth.keyprovider.OpenSSHKeyFile -import net.schmizz.sshj.userauth.keyprovider.PKCS8KeyFile -import net.schmizz.sshj.userauth.keyprovider.PuTTYKeyFile -import net.schmizz.sshj.userauth.password.PasswordFinder -import net.schmizz.sshj.userauth.password.Resource -import com.hierynomus.sshj.userauth.keyprovider.OpenSSHKeyV1KeyFile import org.json.JSONArray import org.json.JSONObject import java.io.File import java.security.KeyFactory import java.security.KeyPair import java.security.KeyPairGenerator -import java.security.MessageDigest -import java.security.PublicKey import java.security.spec.ECGenParameterSpec import java.security.spec.PKCS8EncodedKeySpec import java.security.spec.RSAKeyGenParameterSpec @@ -53,23 +41,6 @@ data class SshKey( val created: Long, ) -/** The public key's SSH form and its fingerprint (SHA256:..., as ssh-keygen -l). */ -object KeyFormat { - /** the key in SSH's wire form (its type, then its fields) */ - fun blob(k: PublicKey): ByteArray = Buffer.PlainBuffer().putPublicKey(k).compactData - - /** the key's SSH type: ssh-ed25519, ecdsa-sha2-nistp256, ssh-rsa... */ - fun type(k: PublicKey): String = KeyType.fromKey(k).toString() - - /** the key's authorized_keys line: its type, its blob in base64, and [comment] if any */ - fun openSsh(k: PublicKey, comment: String = ""): String = - type(k) + " " + Base64.getEncoder().encodeToString(blob(k)) + if (comment.isNotEmpty()) " $comment" else "" - - /** the key's fingerprint, SHA256: and its blob's digest in unpadded base64 */ - fun fingerprint(k: PublicKey): String = - "SHA256:" + Base64.getEncoder().withoutPadding().encodeToString(MessageDigest.getInstance("SHA-256").digest(blob(k))) -} - /** * The app's SSH keys: made here or imported (OpenSSH's, PuTTY's .ppk or * PKCS#8 PEM, with their passphrase); each private @@ -124,31 +95,25 @@ class SshKeys(private val dir: File, private val box: SecretBox) { } /** - * A private key's text (OpenSSH's "BEGIN OPENSSH PRIVATE KEY", or a PEM - * PKCS#8 / PKCS#1 one) imported, opened with [passphrase] if it has one. - * Throws if it can't be read. + * A private key's text (OpenSSH's "BEGIN OPENSSH PRIVATE KEY", a PEM + * PKCS#8 / PKCS#1 / SEC1 one, or PuTTY's .ppk) imported, opened with + * [passphrase] if it has one. Throws if it can't be read. */ fun import(text: String, passphrase: String?, name: String): SshKey { SshSecurity.ensure() - val finder = object : PasswordFinder { - /** [passphrase] for the key (none: empty) */ - override fun reqPassword(resource: Resource<*>?): CharArray = (passphrase ?: "").toCharArray() - /** asked once: a wrong passphrase isn't asked again */ - override fun shouldRetry(resource: Resource<*>?) = false + if (Ppk.isPpk(text)) { + // (a .ppk's comment kept as the key's) + val (kp, comment) = Ppk.read(text, passphrase) + return keep(kp, name, comment.takeIf { it.isNotBlank() }) } - val provider: KeyProvider = when { - Ppk.isPpk(text) -> PuTTYKeyFile().apply { init(text, null, finder) } - text.contains("BEGIN OPENSSH PRIVATE KEY") -> OpenSSHKeyV1KeyFile().apply { init(text, null, finder) } - text.contains("BEGIN") && text.contains("PRIVATE KEY") -> PKCS8KeyFile().apply { init(text, null, finder) } - else -> OpenSSHKeyFile().apply { init(text, null, finder) } - } - // (a .ppk's comment kept as the key's) - return keep(KeyPair(provider.public, provider.private), name, if (Ppk.isPpk(text)) Ppk.comment(text)?.takeIf { it.isNotBlank() } else null) + // (OpenSSH's and PEM's read by libdmodemssh, written again unencrypted for the pair) + val plain = NativeSsh.keyExport(text, passphrase, null) + ?: throw java.io.IOException("the key can't be read: not a private key, or not with that passphrase") + return keep(KeyGen.readOpenSsh(plain).first, name) } - /** [given] kept: its private half sealed in its own file (an RSA one made whole first), its entry added */ - private fun keep(given: KeyPair, name: String, comment: String? = null): SshKey { - val pair = withCrt(given) + /** [pair] kept: its private half sealed in its own file, its entry added */ + private fun keep(pair: KeyPair, name: String, comment: String? = null): SshKey { val id = UUID.randomUUID().toString() val sealed = box.seal( JSONObject() @@ -167,45 +132,7 @@ class SshKeys(private val dir: File, private val box: SecretBox) { return k } - /** - * an RSA key given as n and d only (sshj reads PuTTY's that way) made - * whole: its primes found again from n, e and d, so that it can be - * encoded (Android's provider won't encode one without them) - */ - private fun withCrt(kp: KeyPair): KeyPair { - val priv = kp.private as? java.security.interfaces.RSAPrivateKey ?: return kp - if (priv is java.security.interfaces.RSAPrivateCrtKey) return kp - val pub = kp.public as java.security.interfaces.RSAPublicKey - val n = pub.modulus - val e = pub.publicExponent - val d = priv.privateExponent - val one = java.math.BigInteger.ONE - // k = de - 1 = 2^s t; for random g, a square root of 1 other than ±1 among g^t, g^2t, ... splits n - val k = d.multiply(e).subtract(one) - val s = k.lowestSetBit - val t = k.shiftRight(s) - val rnd = java.security.SecureRandom() - var p: java.math.BigInteger? = null - while (p == null) { - val g = java.math.BigInteger(n.bitLength() - 1, rnd).add(java.math.BigInteger.valueOf(2)) - var x = g.modPow(t, n) - for (i in 0 until s) { - val y = x.multiply(x).mod(n) - if (y == one && x != one && x != n.subtract(one)) { - p = x.subtract(one).gcd(n) - break - } - x = y - } - } - val q = n.divide(p) - val spec = java.security.spec.RSAPrivateCrtKeySpec( - n, e, d, p, q, d.mod(p.subtract(one)), d.mod(q.subtract(one)), q.modInverse(p), - ) - return KeyPair(pub, KeyFactory.getInstance("RSA", "BC").generatePrivate(spec)) - } - - /** the key's pair, opened: for sshj's authentication */ + /** the key's pair, opened */ fun keyPair(id: String): KeyPair { SshSecurity.ensure() val o = JSONObject(String(box.open(File(dir, "$id.key").readBytes()))) @@ -244,8 +171,8 @@ class SshKeys(private val dir: File, private val box: SecretBox) { ) } - /** the key as sshj's key provider, for authentication */ - fun provider(id: String): KeyProvider = KeyPairWrapper(keyPair(id)) + /** the private key's text, unencrypted in OpenSSH's form: for logging in with */ + fun privateText(id: String): String = KeyGen.openSshPrivate(keyPair(id), byId(id)?.let { comment(it) } ?: "") /** the key's name changed to [name] */ fun rename(id: String, name: String) { diff --git a/app/src/main/java/org/dmodem/app/android/ssh/KnownHosts.kt b/app/src/main/java/org/dmodem/app/android/ssh/KnownHosts.kt index 6b2121c..4a3a4e1 100644 --- a/app/src/main/java/org/dmodem/app/android/ssh/KnownHosts.kt +++ b/app/src/main/java/org/dmodem/app/android/ssh/KnownHosts.kt @@ -2,10 +2,7 @@ // Copyright (C) 2026 Neo-Desktop package org.dmodem.app.android.ssh -import net.schmizz.sshj.common.Buffer -import net.schmizz.sshj.transport.verification.HostKeyVerifier import java.io.File -import java.security.PublicKey import java.util.Base64 /** @@ -14,8 +11,7 @@ import java.util.Base64 * the one kept, is put to the user ([ask]): accepted for this connection * only, or kept (in place of the old key, for a changed one). */ -class KnownHosts(private val file: File, private val ask: (Prompt.HostKey, Any?) -> Answer) : HostKeyVerifier { - +class KnownHosts(private val file: File, private val ask: (Prompt.HostKey, Any?) -> Answer) { /** the host as known_hosts names it: bare on port 22, else "[host]:port" */ private fun hostPart(host: String, port: Int) = if (port == 22) host else "[$host]:$port" @@ -34,17 +30,16 @@ class KnownHosts(private val file: File, private val ask: (Prompt.HostKey, Any?) } } - /** [key] kept for the host, in place of a key of its type kept before */ + /** a key ([type], in base64) kept for the host, in place of a key of its type kept before */ @Synchronized - fun keep(host: String, port: Int, key: PublicKey) { + fun keep(host: String, port: Int, type: String, b64: String) { val hp = hostPart(host, port) - val type = KeyFormat.type(key) val others = lines().filterNot { l -> val f = l.trim().split(Regex("\\s+")) f.size >= 2 && f[0].split(',').contains(hp) && f[1] == type } file.parentFile?.mkdirs() - file.writeText((others + "$hp $type ${Base64.getEncoder().encodeToString(KeyFormat.blob(key))}").joinToString("\n", postfix = "\n")) + file.writeText((others + "$hp $type $b64").joinToString("\n", postfix = "\n")) } /** every key kept: (host part as the file has it, type, fingerprint) */ @@ -71,36 +66,54 @@ class KnownHosts(private val file: File, private val ask: (Prompt.HostKey, Any?) .joinToString("\n", postfix = "\n")) } - /** [verify] with no owner for the question */ - override fun verify(hostname: String, port: Int, key: PublicKey): Boolean = verify(hostname, port, key, null) - - /** verify(), the question (if any) asked as [owner]'s: the connection's */ - fun verify(hostname: String, port: Int, key: PublicKey, owner: Any?): Boolean { - val type = KeyFormat.type(key) - val b64 = Base64.getEncoder().encodeToString(KeyFormat.blob(key)) + /** + * the server's key (its OpenSSH line, "ssh-ed25519 AAAA...") checked: + * true if it's the one kept, else as the user answers (asked as + * [owner]'s question: the connection's), kept if they ask + */ + fun verify(hostname: String, port: Int, keyLine: String, owner: Any? = null): Boolean { + val f = keyLine.trim().split(Regex("\\s+")) + if (f.size < 2) return false + val (type, b64) = f val kept = keysFor(hostname, port) if (kept.any { it.first == type && it.second == b64 }) return true val old = kept.firstOrNull { it.first == type }?.second?.let { fingerprintOf(it) } val a = ask( Prompt.HostKey( if (old != null) "The host key has CHANGED" else "Unknown host", - hostname, port, type, KeyFormat.fingerprint(key), old, + hostname, port, type, fingerprintOf(b64), old, ), owner, ) - if (a.accepted && a.remember) keep(hostname, port, key) + if (a.accepted && a.remember) keep(hostname, port, type, b64) return a.accepted } - /** the key types kept for the host, first (so the server is asked for the key we know) */ - override fun findExistingAlgorithms(hostname: String, port: Int): List = - keysFor(hostname, port).map { it.first }.distinct() + /** + * the host key algorithms to ask the server for, those of the keys kept + * for the host first (so it shows the key we know); empty when none are + * kept (libssh's own order) + */ + fun hostKeyAlgorithms(hostname: String, port: Int): List { + val kept = keysFor(hostname, port).map { it.first }.distinct() + if (kept.isEmpty()) return emptyList() + /** a key type's signature algorithms (an RSA key's SHA-2 ones) */ + fun algs(t: String) = if (t == "ssh-rsa") listOf("rsa-sha2-512", "rsa-sha2-256") else listOf(t) + return (kept.flatMap { algs(it) } + ALL).distinct() + } /** the SHA256 fingerprint of a key kept in base64, or "(unreadable)" */ private fun fingerprintOf(b64: String): String = try { - val key = Buffer.PlainBuffer(Base64.getDecoder().decode(b64)).readPublicKey() - KeyFormat.fingerprint(key) + KeyFormat.fingerprint(Base64.getDecoder().decode(b64)) } catch (_: Exception) { "(unreadable)" } + + companion object { + /** the host key algorithms libdmodemssh takes, in libssh's order */ + private val ALL = listOf( + "ssh-ed25519", "ecdsa-sha2-nistp521", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp256", + "rsa-sha2-512", "rsa-sha2-256", + ) + } } diff --git a/app/src/main/java/org/dmodem/app/android/ssh/NativeSsh.kt b/app/src/main/java/org/dmodem/app/android/ssh/NativeSsh.kt new file mode 100644 index 0000000..98df0f6 --- /dev/null +++ b/app/src/main/java/org/dmodem/app/android/ssh/NativeSsh.kt @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package org.dmodem.app.android.ssh + +/** + * libdmodemssh (native-ssh, on libssh), the SSH client every D-Modem app + * shares: each connection a handle, polled on a thread of its own for its + * events; the other calls from any thread. native-ssh/include/dmodemssh.h + * tells what each does. + */ +object NativeSsh { + const val EV_HOSTKEY = 1 + const val EV_AUTH = 2 + const val EV_PROMPTS = 3 + const val EV_READY = 4 + const val EV_OPEN = 5 + const val EV_DATA = 6 + const val EV_EOF = 7 + const val EV_EXIT = 8 + const val EV_CLOSE = 9 + const val EV_INCOMING = 10 + const val EV_LISTEN = 11 + const val EV_CLOSED = 12 + + const val AUTH_PASSWORD = 1 + const val AUTH_PUBLICKEY = 2 + const val AUTH_INTERACTIVE = 4 + + /** an incoming channel that is the agent's (ssh -A) */ + const val IN_AGENT = -1 + + init { + try { + System.loadLibrary("dmodem_ssh_jni") + } catch (e: UnsatisfiedLinkError) { + // (a JVM's tests: loaded already by another class loader, Robolectric's sandboxes + // each their own; a copy of the library is another library to the JVM) + if (e.message?.contains(Regex("another class ?loader", RegexOption.IGNORE_CASE)) != true) throw e + val name = System.mapLibraryName("dmodem_ssh_jni") + val lib = (System.getProperty("java.library.path") ?: "").split(java.io.File.pathSeparator) + .map { java.io.File(it, name) }.firstOrNull { it.isFile } ?: throw e + val copy = java.io.File.createTempFile("dmodem_ssh_jni", ".so").apply { deleteOnExit() } + lib.copyTo(copy, overwrite = true) + System.load(copy.path) + } + } + + /** a connection to make to user@host:port (nothing done until polled): its handle, or 0 */ + @JvmStatic external fun create(host: String, port: Int, user: String): Long + + /** the connection dropped (if it's up) and freed */ + @JvmStatic external fun free(h: Long) + + /** an option, before the first poll ("config", "knownhosts", "hostkeys", "timeout", "compression"): 0, or -1 */ + @JvmStatic external fun option(h: Long, name: String, value: String): Int + + /** + * the next event: [ev] is (1, type, channel, value), (0, ...) when [ms] + * passed with none, or (-1, ...) once the connection is over; the + * event's data, if it has any + */ + @JvmStatic external fun poll(h: Long, ms: Int, ev: IntArray): ByteArray? + + /** the connection closed by the user: an EV_CLOSED with no reason comes */ + @JvmStatic external fun disconnect(h: Long) + + /** the server's key trusted ([ok]) or not; [remember]: added to the known_hosts option's file */ + @JvmStatic external fun trust(h: Long, ok: Boolean, remember: Boolean) + + /** a login by password */ + @JvmStatic external fun authPassword(h: Long, password: String) + + /** a login by a private key's text: 0, or -1 when it can't be read with [passphrase] (nothing tried) */ + @JvmStatic external fun authKey(h: Long, key: String, passphrase: String?): Int + + /** a login by the server's questions (keyboard-interactive) */ + @JvmStatic external fun authInteractive(h: Long) + + /** no more logins tried: the connection closes */ + @JvmStatic external fun authCancel(h: Long) + + /** an EV_PROMPTS round's instruction */ + @JvmStatic external fun instruction(h: Long): String + + /** an EV_PROMPTS round's question [i] ([echo]'s first: whether its answer may be shown) */ + @JvmStatic external fun prompt(h: Long, i: Int, echo: BooleanArray): String + + /** the answer to question [i] */ + @JvmStatic external fun answer(h: Long, i: Int, answer: String) + + /** the round's answers sent */ + @JvmStatic external fun answered(h: Long) + + /** a shell on a pty: its channel, or -1 */ + @JvmStatic external fun shell(h: Long, term: String, cols: Int, rows: Int, agent: Boolean): Int + + /** a command run, with no pty: its channel, or -1 */ + @JvmStatic external fun exec(h: Long, command: String, agent: Boolean): Int + + /** a TCP connection from the server to host:port, for one from [from]:[fromPort]: its channel, or -1 */ + @JvmStatic external fun direct(h: Long, host: String, port: Int, from: String, fromPort: Int): Int + + /** the server asked to listen on [address]:[port] (null: its default; 0: a port it picks): the request's number, or -1 */ + @JvmStatic external fun listen(h: Long, address: String?, port: Int): Int + + /** that listen stopped */ + @JvmStatic external fun unlisten(h: Long, address: String?, port: Int) + + /** data to a channel: the bytes still kept for the server's window, or -1 if it isn't open */ + @JvmStatic external fun write(h: Long, channel: Int, data: ByteArray, offset: Int, length: Int): Int + + /** the channel's end of data sent */ + @JvmStatic external fun eof(h: Long, channel: Int) + + /** the channel closed (an EV_CLOSE comes) */ + @JvmStatic external fun close(h: Long, channel: Int) + + /** a shell's pty resized */ + @JvmStatic external fun resize(h: Long, channel: Int, cols: Int, rows: Int) + + /** a private key (OpenSSH's, PEM) written again in OpenSSH's form under [newPassphrase] (empty: none), or null if it can't be read */ + @JvmStatic external fun keyExport(key: String, passphrase: String?, newPassphrase: String?): String? +} diff --git a/app/src/main/java/org/dmodem/app/android/ssh/Ppk.kt b/app/src/main/java/org/dmodem/app/android/ssh/Ppk.kt index 81b43da..a740fd0 100644 --- a/app/src/main/java/org/dmodem/app/android/ssh/Ppk.kt +++ b/app/src/main/java/org/dmodem/app/android/ssh/Ppk.kt @@ -2,11 +2,9 @@ // Copyright (C) 2026 Neo-Desktop package org.dmodem.app.android.ssh -import net.schmizz.sshj.common.Buffer import org.bouncycastle.crypto.generators.Argon2BytesGenerator import org.bouncycastle.crypto.params.Argon2Parameters -import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters -import org.bouncycastle.crypto.util.PrivateKeyFactory +import java.io.IOException import java.security.KeyPair import java.security.MessageDigest import java.security.SecureRandom @@ -22,7 +20,7 @@ import javax.crypto.spec.SecretKeySpec * PuTTY's private key files (.ppk), as PuTTYgen writes them: version 3 * (Argon2id, AES-256-CBC, HMAC-SHA-256; PuTTY 0.75 and on) or version 2 * (SHA-1, for older PuTTY and the tools that only read it, WinSCP's older - * releases among them). Read back by sshj's PuTTYKeyFile. + * releases among them); and read, of either version. */ object Ppk { @@ -51,49 +49,17 @@ object Ppk { } val headers = StringBuilder() - val cipherKey: ByteArray - val iv: ByteArray - val macKey: ByteArray val salt = ByteArray(16).also { SecureRandom().nextBytes(it) } - if (version == 3) { - if (encrypted) { - val out = ByteArray(80) - Argon2BytesGenerator().apply { - init( - Argon2Parameters.Builder(Argon2Parameters.ARGON2_id) - .withVersion(Argon2Parameters.ARGON2_VERSION_13) - .withMemoryAsKB(argon.memoryKiB).withIterations(argon.passes) - .withParallelism(argon.parallelism).withSalt(salt).build(), - ) - }.generateBytes(passphrase.toByteArray(), out) - cipherKey = out.copyOfRange(0, 32) - iv = out.copyOfRange(32, 48) - macKey = out.copyOfRange(48, 80) - headers.append("Key-Derivation: Argon2id\n") - headers.append("Argon2-Memory: ${argon.memoryKiB}\n") - headers.append("Argon2-Passes: ${argon.passes}\n") - headers.append("Argon2-Parallelism: ${argon.parallelism}\n") - headers.append("Argon2-Salt: ${hex(salt)}\n") - } else { - cipherKey = ByteArray(0); iv = ByteArray(0); macKey = ByteArray(0) - } - } else { - /** the SHA-1 of [parts] one after another */ - fun sha1(vararg parts: ByteArray) = MessageDigest.getInstance("SHA-1").run { parts.forEach { update(it) }; digest() } - val p = passphrase.toByteArray() - cipherKey = (sha1(byteArrayOf(0, 0, 0, 0), p) + sha1(byteArrayOf(0, 0, 0, 1), p)).copyOf(32) - iv = ByteArray(16) - macKey = sha1("putty-private-key-file-mac-key".toByteArray(), if (encrypted) p else ByteArray(0)) + if (version == 3 && encrypted) { + headers.append("Key-Derivation: Argon2id\n") + headers.append("Argon2-Memory: ${argon.memoryKiB}\n") + headers.append("Argon2-Passes: ${argon.passes}\n") + headers.append("Argon2-Parallelism: ${argon.parallelism}\n") + headers.append("Argon2-Salt: ${hex(salt)}\n") } + val (cipherKey, iv, macKey) = keys(version, passphrase, Argon2Parameters.ARGON2_id, argon, salt) - val macData = Buffer.PlainBuffer().putString(alg).putString(encryption).putString(comment) - .putBytes(pub).putBytes(priv).compactData - val macAlg = if (version == 3) "HmacSHA256" else "HmacSHA1" - val mac = Mac.getInstance(macAlg).run { - // (an empty key, for an unencrypted v3 file: HMAC's own zero-length key) - init(if (macKey.isEmpty()) EmptyKey(macAlg) else SecretKeySpec(macKey, macAlg)) - doFinal(macData) - } + val mac = mac(version, macKey, alg, encryption, comment, pub, priv) val privOut = if (encrypted) { Cipher.getInstance("AES/CBC/NoPadding").run { init(Cipher.ENCRYPT_MODE, SecretKeySpec(cipherKey, "AES"), IvParameterSpec(iv)) @@ -114,6 +80,122 @@ object Ppk { return sb.toString() } + /** + * the file's cipher key, IV and MAC key from [passphrase] (empty: none): + * v3's from Argon2 of [argonType] with [argon] and [salt], v2's by SHA-1 + */ + private fun keys(version: Int, passphrase: String, argonType: Int, argon: Argon, salt: ByteArray): Triple { + val p = passphrase.toByteArray() + if (version == 3) { + if (passphrase.isEmpty()) return Triple(ByteArray(0), ByteArray(0), ByteArray(0)) + val out = ByteArray(80) + Argon2BytesGenerator().apply { + init( + Argon2Parameters.Builder(argonType) + .withVersion(Argon2Parameters.ARGON2_VERSION_13) + .withMemoryAsKB(argon.memoryKiB).withIterations(argon.passes) + .withParallelism(argon.parallelism).withSalt(salt).build(), + ) + }.generateBytes(p, out) + return Triple(out.copyOfRange(0, 32), out.copyOfRange(32, 48), out.copyOfRange(48, 80)) + } + /** the SHA-1 of [parts] one after another */ + fun sha1(vararg parts: ByteArray) = MessageDigest.getInstance("SHA-1").run { parts.forEach { update(it) }; digest() } + return Triple( + (sha1(byteArrayOf(0, 0, 0, 0), p) + sha1(byteArrayOf(0, 0, 0, 1), p)).copyOf(32), + ByteArray(16), + sha1("putty-private-key-file-mac-key".toByteArray(), p), + ) + } + + /** the file's MAC: over its type, encryption, comment and both blobs (the private one decrypted, padded) */ + private fun mac(version: Int, macKey: ByteArray, alg: String, encryption: String, comment: String, pub: ByteArray, priv: ByteArray): ByteArray { + val data = SshWriter().string(alg).string(encryption).string(comment).bytes(pub).bytes(priv).bytes() + val macAlg = if (version == 3) "HmacSHA256" else "HmacSHA1" + return Mac.getInstance(macAlg).run { + // (an empty key, for an unencrypted v3 file: HMAC's own zero-length key) + init(if (macKey.isEmpty()) EmptyKey(macAlg) else SecretKeySpec(macKey, macAlg)) + doFinal(data) + } + } + + /** + * A .ppk read (version 2 or 3), opened with [passphrase] if it's + * encrypted: the key and its comment. Throws if it can't be (a wrong + * passphrase among the reasons: its MAC then differs). + */ + fun read(text: String, passphrase: String?): Pair { + val lines = text.lines().map { it.trimEnd('\r') } + val head = mutableMapOf() + var pub = ByteArray(0) + var privData = ByteArray(0) + var i = 0 + /** the next [n] lines as base64 */ + fun block(n: Int) = Base64.getDecoder().decode(lines.subList(i, i + n).joinToString("")).also { i += n } + while (i < lines.size) { + val l = lines[i++] + val colon = l.indexOf(": ") + if (colon < 0) continue + val k = l.substring(0, colon) + val v = l.substring(colon + 2) + when (k) { + "Public-Lines" -> pub = block(v.trim().toInt()) + "Private-Lines" -> privData = block(v.trim().toInt()) + else -> head[k] = v + } + } + val first = head.keys.firstOrNull { it.startsWith("PuTTY-User-Key-File-") } ?: throw IOException("not a PuTTY key") + val version = first.removePrefix("PuTTY-User-Key-File-").toInt() + if (version != 2 && version != 3) throw IOException("PuTTY key files of version $version can't be read") + val alg = head.getValue(first).trim() + val encryption = head["Encryption"]?.trim() ?: "none" + val comment = head["Comment"] ?: "" + val encrypted = when (encryption) { + "none" -> false + "aes256-cbc" -> true + else -> throw IOException("PuTTY's $encryption encryption can't be read") + } + val pass = if (encrypted) passphrase?.takeIf { it.isNotEmpty() } ?: throw IOException("the key needs its passphrase") else "" + val argonType = when (head["Key-Derivation"]?.trim()) { + "Argon2d" -> Argon2Parameters.ARGON2_d + "Argon2i" -> Argon2Parameters.ARGON2_i + else -> Argon2Parameters.ARGON2_id + } + val argon = Argon( + head["Argon2-Memory"]?.trim()?.toInt() ?: 0, + head["Argon2-Passes"]?.trim()?.toInt() ?: 0, + head["Argon2-Parallelism"]?.trim()?.toInt() ?: 0, + ) + val salt = head["Argon2-Salt"]?.trim()?.chunked(2)?.map { it.toInt(16).toByte() }?.toByteArray() ?: ByteArray(0) + val (cipherKey, iv, macKey) = keys(version, pass, argonType, argon, salt) + val priv = if (encrypted) { + Cipher.getInstance("AES/CBC/NoPadding").run { + init(Cipher.DECRYPT_MODE, SecretKeySpec(cipherKey, "AES"), IvParameterSpec(iv)) + doFinal(privData) + } + } else { + privData + } + val want = head["Private-MAC"]?.trim() ?: throw IOException("the key has no MAC") + if (!MessageDigest.isEqual(hex(mac(version, macKey, alg, encryption, comment, pub, priv)).toByteArray(), want.lowercase().toByteArray())) { + throw IOException(if (encrypted) "the passphrase is wrong" else "the key's MAC is wrong") + } + val public = KeyFormat.fromBlob(pub) + val r = SshReader(priv) + val private = when (public) { + is java.security.interfaces.RSAPublicKey -> { + val d = r.mpint() + val p = r.mpint() + val q = r.mpint() + KeyGen.rsaPrivate(public.modulus, public.publicExponent, d, p, q) + } + is java.security.interfaces.ECPublicKey -> + KeyGen.ecPrivate(KeyFormat.curve(public.params.curve.field.fieldSize).first, r.mpint()) + else -> KeyGen.ed25519Private(r.bytes()) + } + return KeyPair(public, private) to comment + } + /** an HMAC key of no bytes (SecretKeySpec won't make one) */ private class EmptyKey(private val alg: String) : javax.crypto.SecretKey { /** the key's algorithm, the MAC's */ @@ -126,13 +208,13 @@ object Ppk { /** the private half's fields as PuTTY's private blob has them (RSA's d, p, q, iqmp; ECDSA's s; Ed25519's seed) */ private fun privateBlob(kp: KeyPair): ByteArray { - val b = Buffer.PlainBuffer() + val b = SshWriter() when (val p = kp.private) { - is RSAPrivateCrtKey -> b.putMPInt(p.privateExponent).putMPInt(p.primeP).putMPInt(p.primeQ).putMPInt(p.crtCoefficient) - is ECPrivateKey -> b.putMPInt(p.s) - else -> b.putBytes((PrivateKeyFactory.createKey(p.encoded) as Ed25519PrivateKeyParameters).encoded) + is RSAPrivateCrtKey -> b.mpint(p.privateExponent).mpint(p.primeP).mpint(p.primeQ).mpint(p.crtCoefficient) + is ECPrivateKey -> b.mpint(p.s) + else -> b.bytes(KeyGen.ed25519Seed(p)) } - return b.compactData + return b.bytes() } /** [data] in base64, in lines of 64 */ diff --git a/app/src/main/java/org/dmodem/app/android/ssh/Secrets.kt b/app/src/main/java/org/dmodem/app/android/ssh/Secrets.kt index 14a5182..426df6d 100644 --- a/app/src/main/java/org/dmodem/app/android/ssh/Secrets.kt +++ b/app/src/main/java/org/dmodem/app/android/ssh/Secrets.kt @@ -106,14 +106,14 @@ class PasswordStore(private val file: File, private val box: SecretBox) { } /** - * The full BouncyCastle as "BC": Android's own is cut down (no Ed25519, - * no X25519 for sshj), so it goes, and sshj uses this one. + * The full BouncyCastle as "BC": Android's own is cut down (no Ed25519), + * so it goes; the keys are made, read and used for the agent with this one. */ object SshSecurity { @Volatile private var done = false - /** the full BouncyCastle in place as "BC" and sshj told to use it (once) */ + /** the full BouncyCastle in place as "BC" (once) */ @Synchronized fun ensure() { if (done) return @@ -122,8 +122,6 @@ object SshSecurity { Security.removeProvider("BC") Security.addProvider(org.bouncycastle.jce.provider.BouncyCastleProvider()) } - net.schmizz.sshj.common.SecurityUtils.setRegisterBouncyCastle(false) - net.schmizz.sshj.common.SecurityUtils.setSecurityProvider("BC") done = true } } diff --git a/app/src/main/java/org/dmodem/app/android/ssh/SshLink.kt b/app/src/main/java/org/dmodem/app/android/ssh/SshLink.kt index 1690e97..b62d2af 100644 --- a/app/src/main/java/org/dmodem/app/android/ssh/SshLink.kt +++ b/app/src/main/java/org/dmodem/app/android/ssh/SshLink.kt @@ -6,38 +6,27 @@ import org.dmodem.app.android.terminal.TerminalLink import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow -import net.schmizz.sshj.DefaultConfig -import net.schmizz.sshj.SSHClient -import net.schmizz.sshj.connection.channel.direct.Session -import net.schmizz.sshj.transport.TransportException -import net.schmizz.sshj.userauth.UserAuthException -import net.schmizz.sshj.userauth.keyprovider.KeyProvider -import net.schmizz.sshj.userauth.method.AuthKeyboardInteractive -import net.schmizz.sshj.userauth.method.AuthMethod -import net.schmizz.sshj.userauth.method.AuthPassword -import net.schmizz.sshj.userauth.method.ChallengeResponseProvider -import net.schmizz.sshj.userauth.password.PasswordFinder -import net.schmizz.sshj.userauth.password.Resource -import java.io.IOException -import java.io.InputStream -import java.io.OutputStream +import java.io.ByteArrayOutputStream import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit /** - * An SSH connection's interactive shell: host key checked against - * [KnownHosts], the user authenticated by a key, or by password or the - * server's questions (keyboard-interactive) asked of the user, a pty of - * [term] in the terminal's size; its output (stdout and stderr) to the - * listeners, the window's size to the server as it changes. [connect] - * starts it on a thread of its own. + * An SSH connection's interactive shell, on libdmodemssh (the apps' own + * client, on libssh): host key checked against [KnownHosts], the user + * authenticated by a key, or by password or the server's questions + * (keyboard-interactive) asked of the user, a pty of [term] in the + * terminal's size; its output (stdout and stderr) to the listeners, the + * window's size to the server as it changes. [connect] starts it on a + * thread of its own, which polls the connection for its events. */ class SshLink( val host: String, val port: Int, val user: String, - /** a key to log in with, or null for passwords */ - private val key: KeyProvider?, + /** a private key's text (OpenSSH's, unencrypted) to log in with, or null for passwords */ + private val key: String?, private val knownHosts: KnownHosts, /** the user asked (from the connection's thread), with the link as the asker */ private val ask: (Prompt, Any) -> Answer, @@ -50,21 +39,36 @@ class SshLink( private val term: String = "xterm-256color", @Volatile private var cols: Int = 80, @Volatile private var rows: Int = 24, - private val keepAliveSec: Int = 30, /** port forwards started once logged in */ private val forwardSpecs: List = emptyList(), /** the keys offered to the server as an agent (ssh -A); null: no agent forwarding */ private val agent: AgentKeys? = null, -) : TerminalLink { +) : TerminalLink, SshChannels { private val _state = MutableStateFlow(TerminalLink.State.Connecting) override val state: StateFlow = _state.asStateFlow() private val listeners = CopyOnWriteArrayList() private val io = Executors.newSingleThreadExecutor { r -> Thread(r, "ssh-$host-io").apply { isDaemon = true } } + private val agentIo = Executors.newSingleThreadExecutor { r -> Thread(r, "ssh-$host-agent").apply { isDaemon = true } } - @Volatile private var client: SSHClient? = null - @Volatile private var shell: Session.Shell? = null - @Volatile private var out: OutputStream? = null + /** the connection (0 before it's made and once it's freed), its channels' handlers: all under [lock] */ + private val lock = Any() + private var h = 0L + private var ready = false + private val handlers = HashMap() + /** channels whose number was taken again before their close was handed over: those closes to ignore */ + private val staleCloses = HashMap() + private val listens = HashMap Unit>() + + // (the connection's thread's own) + @Volatile private var shell = -1 + @Volatile private var shellHandler: ChannelHandler? = null + @Volatile private var started = false + private var triedKey = false + private var tries = 0 + private var saved = savedPassword + private var authStarted = false + private var why: String? = null @Volatile private var closing = false @Volatile private var fwd: Forwards? = null @@ -76,7 +80,7 @@ class SshLink( /** what the forwards and the agent did (the latest last, at most [MAX_EVENTS]) */ val events: StateFlow> = _events.asStateFlow() - /** the agent was forwarded: the server took the request */ + /** the agent was forwarded: asked of the server with the shell */ @Volatile var agentForwarded = false private set @@ -97,139 +101,287 @@ class SshLink( /** the connection made, in a thread of its own */ fun connect() { + started = true Thread({ run() }, "ssh-$host").apply { isDaemon = true }.start() } - /** the connection's life on its thread: connect, log in, start forwards and the agent, open the shell and read it until it ends */ + /** the connection's life on its thread: each event acted on until it's over, then it's freed */ private fun run() { - try { - SshSecurity.ensure() - val c = SSHClient(DefaultConfig()) - client = c - // (the host key's question asked as this link's: cancelled if it closes) - c.addHostKeyVerifier(object : net.schmizz.sshj.transport.verification.HostKeyVerifier { - /** the host's key checked against [knownHosts], the user asked of a new or changed one */ - override fun verify(hostname: String, port: Int, key: java.security.PublicKey) = - knownHosts.verify(hostname, port, key, this@SshLink) + val c = try { + NativeSsh.create(host, port, user) + } catch (e: Throwable) { + // (no native library: nothing to connect with) + return closed("SSH isn't available: ${e.message ?: e.javaClass.simpleName}") + } + if (c == 0L) return closed("could not start SSH") + NativeSsh.option(c, "timeout", "20") + knownHosts.hostKeyAlgorithms(host, port).takeIf { it.isNotEmpty() }?.let { + NativeSsh.option(c, "hostkeys", it.joinToString(",")) + } + synchronized(lock) { + if (closing) { + NativeSsh.free(c) + return closed(null) + } + h = c + } + val ev = IntArray(4) + var reason: String? = null + while (true) { + val data = NativeSsh.poll(c, 1000, ev) + if (ev[0] < 0) break + if (ev[0] == 0) continue + if (ev[1] == NativeSsh.EV_CLOSED) { + reason = data?.let { String(it) } + break + } + try { + event(c, ev[1], ev[2], ev[3], data) + } catch (e: RuntimeException) { + why = why ?: (e.message ?: e.javaClass.simpleName) + NativeSsh.disconnect(c) + } + } + // (no more calls from other threads; then the channels told, then it's freed) + val left: Collection + synchronized(lock) { + h = 0L + ready = false + left = handlers.values.toList() + handlers.clear() + listens.clear() + } + for (x in left) runCatching { x.closed() } + NativeSsh.free(c) + closed( + when { + closing -> null + why != null -> why + authStarted && shell < 0 && reason != null -> "authentication failed: $reason" + reason != null && shell < 0 -> reason + else -> "connection closed by $host" + }, + ) + } - /** the key algorithms [knownHosts] already has for the host, preferred in the handshake */ - override fun findExistingAlgorithms(hostname: String, port: Int): List = - knownHosts.findExistingAlgorithms(hostname, port) - }) - c.connectTimeout = 20_000 - c.connect(host, port) - c.connection.keepAlive.keepAliveInterval = keepAliveSec - authenticate(c) - val f = Forwards(c, _forwards, ::event) - fwd = f - for (spec in forwardSpecs) f.start(spec) - val session = AgentSession(c.connection) - session.open() - if (agent != null) { - c.connection.attach(AgentForwarder(c.connection, AgentServer(agent, this@SshLink, ::event))) - agentForwarded = session.requestAgentForwarding() - event(if (agentForwarded) "agent forwarded" else "the server refused agent forwarding") + /** one event of the connection's (not its last) acted on */ + private fun event(c: Long, type: Int, channel: Int, value: Int, data: ByteArray?) { + when (type) { + NativeSsh.EV_HOSTKEY -> { + val ok = knownHosts.verify(host, port, data?.let { String(it) } ?: "", this) + if (!ok) why = "the host key wasn't accepted" + NativeSsh.trust(c, ok, false) + } + NativeSsh.EV_AUTH -> login(c, value, data?.let { String(it) } ?: "") + NativeSsh.EV_PROMPTS -> questions(c, value, data?.let { String(it) } ?: "") + NativeSsh.EV_READY -> ready(c, data) + NativeSsh.EV_INCOMING -> incoming(c, channel, value) + NativeSsh.EV_LISTEN -> synchronized(lock) { listens.remove(channel) } + ?.invoke(value, data?.let { String(it) }) + else -> { + val x = synchronized(lock) { + if (type == NativeSsh.EV_CLOSE) { + val stale = staleCloses[channel] + if (stale != null) { + if (stale <= 1) staleCloses.remove(channel) else staleCloses[channel] = stale - 1 + null + } else { + handlers.remove(channel) + } + } else { + handlers[channel] + } + } ?: return + when (type) { + NativeSsh.EV_OPEN -> x.opened(value != 0, data?.let { String(it) }) + NativeSsh.EV_DATA -> if (data != null) x.data(data, value != 0) + NativeSsh.EV_EOF -> x.eof() + NativeSsh.EV_EXIT -> x.exit(value) + NativeSsh.EV_CLOSE -> x.closed() + } } - session.allocatePTY(term, cols, rows, 0, 0, emptyMap()) - val sh = session.startShell() - shell = sh - out = sh.outputStream - _state.value = TerminalLink.State.Open - pump(sh.errorStream, "stderr") - pump(sh.inputStream, null) - closed(if (closing) null else "connection closed by $host") - } catch (e: UserAuthException) { - closed("authentication failed" + (e.message?.let { ": $it" } ?: "")) - } catch (e: TransportException) { - closed( - if (e.message?.contains("HostKey", ignoreCase = true) == true || e.message?.contains("verify", ignoreCase = true) == true) { - "the host key wasn't accepted" - } else { - e.message ?: "transport error" - }, - ) - } catch (e: IOException) { - closed(if (closing) null else (e.message ?: e.javaClass.simpleName)) - } catch (e: RuntimeException) { - closed(e.message ?: e.javaClass.simpleName) } } - /** the user logged in: by [key] if there is one, else by password (the saved one first) or the server's questions */ - private fun authenticate(c: SSHClient) { + /** + * the next login: by [key] if there is one (and only by it), else by + * password (the saved one first) or the server's questions, [MAX_TRIES] + * times at most + */ + private fun login(c: Long, methods: Int, failed: String) { + authStarted = true if (key != null) { - c.authPublickey(user, key) - return + if (!triedKey && methods and NativeSsh.AUTH_PUBLICKEY != 0) { + triedKey = true + if (NativeSsh.authKey(c, key, null) == 0) return + why = "authentication failed: the key can't be read" + } + return NativeSsh.authCancel(c) } - var tries = 0 - var saved = savedPassword - val finder = object : PasswordFinder { - /** the password: the saved one first, then the user's, kept if they asked; null if they cancelled */ - override fun reqPassword(resource: Resource<*>?): CharArray? { - tries++ - saved?.let { saved = null; return it.toCharArray() } - val a = ask(Prompt.Password("Password", "$user@$host", canRemember = true), this@SshLink) - val p = a.text ?: return null + val password = methods and NativeSsh.AUTH_PASSWORD != 0 + val interactive = methods and NativeSsh.AUTH_INTERACTIVE != 0 + if (password && saved != null) { + val p = saved!! + saved = null + return NativeSsh.authPassword(c, p) + } + if (++tries > MAX_TRIES) return NativeSsh.authCancel(c) + when { + password -> { + val a = ask(Prompt.Password("Password", "$user@$host", canRemember = true), this) + val p = a.text ?: return NativeSsh.authCancel(c) if (a.remember) keepPassword(p) - return p.toCharArray() + NativeSsh.authPassword(c, p) } - - /** another password asked for while under [MAX_TRIES] tries */ - override fun shouldRetry(resource: Resource<*>?) = tries < MAX_TRIES + interactive -> NativeSsh.authInteractive(c) + else -> NativeSsh.authCancel(c) } - val questions = object : ChallengeResponseProvider { - private var name = "" - private var instruction = "" - private var answered = false - /** no particular submethods asked for */ - override fun getSubmethods(): List = emptyList() - /** a new round of questions: its name and instruction kept for the dialogs */ - override fun init(resource: Resource<*>?, name: String?, instruction: String?) { - this.name = name ?: "" - this.instruction = instruction ?: "" - answered = false - } - - /** the user's answer to the server's one question, or null if they cancelled */ - override fun getResponse(prompt: String?, echo: Boolean): CharArray? { - // (one question at a time from sshj: each its own dialog) - val a = ask( - Prompt.Questions( - name.ifEmpty { "$user@$host" }, instruction, listOf((prompt ?: "") to echo), - ), - this@SshLink, - ) - answered = true - return a.texts?.firstOrNull()?.toCharArray() - } - - /** asked again only if the user didn't answer, and under [MAX_TRIES] tries */ - override fun shouldRetry(): Boolean = !answered && tries++ < MAX_TRIES - } - val methods: List = listOf(AuthPassword(finder), AuthKeyboardInteractive(questions)) - c.auth(user, methods) } - /** [s] read to the listeners: on a thread of its own when [name]d (stderr), else on this one */ - private fun pump(s: InputStream, name: String?) { - if (name != null) { - Thread({ read(s) }, "ssh-$host-$name").apply { isDaemon = true }.start() + /** a round of the server's questions put to the user ([name] the round's title), or answered by the saved password */ + private fun questions(c: Long, count: Int, name: String) { + if (count == 0) return NativeSsh.answered(c) + val echo = BooleanArray(1) + val qs = (0 until count).map { NativeSsh.prompt(c, it, echo) to echo[0] } + val instruction = NativeSsh.instruction(c) + // (a password asked as a question: the saved one, if there is one) + val s = saved + if (s != null && count == 1 && !qs[0].second) { + saved = null + NativeSsh.answer(c, 0, s) + return NativeSsh.answered(c) + } + val a = ask(Prompt.Questions(name.ifEmpty { "$user@$host" }, instruction, qs), this) + val texts = a.texts ?: return NativeSsh.authCancel(c) + texts.forEachIndexed { i, t -> NativeSsh.answer(c, i, t) } + NativeSsh.answered(c) + } + + /** logged in: the server's banner shown, the forwards started, the shell asked for (with the agent, when it's forwarded) */ + private fun ready(c: Long, banner: ByteArray?) { + synchronized(lock) { ready = true } + if (banner != null && banner.isNotEmpty()) { + val b = String(banner).replace("\r\n", "\n").replace("\n", "\r\n").toByteArray() + for (l in listeners) l.onData(b, b.size) + } + val f = Forwards(this, _forwards, ::event) + fwd = f + for (spec in forwardSpecs) f.start(spec) + val sh = object : ChannelHandler { + /** the shell open, or refused: the link with it */ + override fun opened(ok: Boolean, why: String?) { + if (ok) { + _state.value = TerminalLink.State.Open + } else { + this@SshLink.why = "the server refused the shell" + (why?.let { ": $it" } ?: "") + NativeSsh.disconnect(c) + } + } + + /** the shell's output (stderr too), to the listeners */ + override fun data(b: ByteArray, stderr: Boolean) { + for (l in listeners) l.onData(b, b.size) + } + + /** the shell over: so is the connection */ + override fun closed() { + synchronized(lock) { if (h != 0L) NativeSsh.disconnect(h) } + } + } + shellHandler = sh + shell = register(sh) { NativeSsh.shell(it, term, cols, rows, agent != null) } + if (shell < 0) { + why = "the shell couldn't be opened" + return NativeSsh.disconnect(c) + } + if (agent != null) { + agentForwarded = true + event("agent forwarded") + } + } + + /** a channel the server opened: the agent's, or a remote forward's connection; closed if it's neither */ + private fun incoming(c: Long, channel: Int, port: Int) { + val x: ChannelHandler? = if (port == NativeSsh.IN_AGENT) { + agent?.let { agentChannel(channel, it) } } else { - read(s) + fwd?.incoming(channel, port) + } + if (x == null) return NativeSsh.close(c, channel) + synchronized(lock) { handlers[channel] = x } + } + + /** an agent channel: its requests answered by an [AgentServer] of its own, off the connection's thread (a signature may ask the user) */ + private fun agentChannel(channel: Int, keys: AgentKeys): ChannelHandler { + val server = AgentServer(keys, this, ::event) + return object : ChannelHandler { + /** requests, answered in order */ + override fun data(b: ByteArray, stderr: Boolean) { + val me = this + runCatching { + agentIo.execute { + val reply = server.feed(b) + if (reply == null) { + close(channel, me) + } else if (reply.isNotEmpty()) { + write(channel, me, reply, 0, reply.size) + } + } + } + } + + /** no more requests: the channel closed */ + override fun eof() { + close(channel, this) + } } } - /** [s] to the listeners until it ends or fails */ - private fun read(s: InputStream) { - val buf = ByteArray(8192) - try { - while (true) { - val n = s.read(buf) - if (n < 0) break - if (n > 0) for (l in listeners) l.onData(buf, n) + /** a channel made by [make] (given the connection) and its handler kept, under the lock: its number, or -1 */ + private fun register(x: ChannelHandler, make: (Long) -> Int): Int = synchronized(lock) { + if (h == 0L || !ready) return -1 + val n = make(h) + if (n > 0) { + // (a number whose close is on its way: that close isn't this one's) + handlers.put(n, x)?.let { old -> + staleCloses[n] = (staleCloses[n] ?: 0) + 1 + runCatching { old.closed() } } - } catch (_: IOException) { } + n + } + + /** a TCP connection from the server, for a forward */ + override fun direct(host: String, port: Int, from: String, fromPort: Int, x: ChannelHandler): Int = + register(x) { NativeSsh.direct(it, host, port, from, fromPort) } + + /** the server asked to listen, for a remote forward */ + override fun listen(address: String?, port: Int, done: (Int, String?) -> Unit): Boolean = synchronized(lock) { + if (h == 0L || !ready) return false + val id = NativeSsh.listen(h, address, port) + if (id < 0) return false + listens[id] = done + true + } + + /** a remote forward's listen stopped */ + override fun unlisten(address: String?, port: Int) { + synchronized(lock) { if (h != 0L) NativeSsh.unlisten(h, address, port) } + } + + /** data to a channel, if it's still [x]'s */ + override fun write(channel: Int, x: ChannelHandler, data: ByteArray, offset: Int, length: Int): Int = synchronized(lock) { + if (h == 0L || handlers[channel] !== x) -1 else NativeSsh.write(h, channel, data, offset, length) + } + + /** a channel's end of data sent, if it's still [x]'s */ + override fun eof(channel: Int, x: ChannelHandler) { + synchronized(lock) { if (h != 0L && handlers[channel] === x) NativeSsh.eof(h, channel) } + } + + /** a channel closed, if it's still [x]'s */ + override fun close(channel: Int, x: ChannelHandler) { + synchronized(lock) { if (h != 0L && handlers[channel] === x) NativeSsh.close(h, channel) } } /** a forward started on the open connection; false if it couldn't be (its error in [forwards]) */ @@ -241,53 +393,60 @@ class SshLink( } /** - * a command run on the server (beside the shell): its exit status and - * output (stdout then stderr), or null with no connection + * a command run on the server (beside the shell, with the agent if + * it's forwarded): its exit status and output (stdout then stderr), or + * null with no connection */ fun exec(command: String, timeoutSec: Long = 30): Pair? { - val c = client ?: return null if (_state.value !is TerminalLink.State.Open) return null - AgentSession(c.connection).use { s -> - s.open() - // (the agent is asked for per session: this one's too) - if (agentForwarded) s.requestAgentForwarding() - val cmd = s.exec(command) - val out = cmd.inputStream.readBytes() - val err = cmd.errorStream.readBytes() - cmd.join(timeoutSec, java.util.concurrent.TimeUnit.SECONDS) - return cmd.exitStatus to (String(out) + String(err)) + val out = ByteArrayOutputStream() + val err = ByteArrayOutputStream() + val done = CountDownLatch(1) + var code: Int? = null + val x = object : ChannelHandler { + /** refused: done */ + override fun opened(ok: Boolean, why: String?) { + if (!ok) err.write((why ?: "refused").toByteArray()) + } + + /** its output, kept */ + override fun data(b: ByteArray, stderr: Boolean) { + synchronized(out) { (if (stderr) err else out).write(b) } + } + + /** its exit status, kept */ + override fun exit(status: Int) { + synchronized(out) { code = status } + } + + /** over */ + override fun closed() { + done.countDown() + } } + val ch = register(x) { NativeSsh.exec(it, command, agentForwarded) } + if (ch < 0) return null + if (!done.await(timeoutSec, TimeUnit.SECONDS)) close(ch, x) + return synchronized(out) { code to (String(out.toByteArray()) + String(err.toByteArray())) } } - /** the link closed, with [reason] (null: the user's doing): its questions cancelled, forwards and connection closed; once */ + /** the link closed, with [reason] (null: the user's doing): its questions cancelled, forwards closed; once */ private fun closed(reason: String?) { if (_state.value is TerminalLink.State.Closed) return _state.value = TerminalLink.State.Closed(reason) cancelAsks(this) fwd?.close() - try { - client?.disconnect() - } catch (_: IOException) { - } io.shutdown() + agentIo.shutdown() } /** [length] bytes of [data] queued to the shell, off the caller's thread; false if it isn't open */ override fun write(data: ByteArray, offset: Int, length: Int): Boolean { - val o = out ?: return false + val x = shellHandler ?: return false if (_state.value !is TerminalLink.State.Open) return false - // (off the caller's thread: the UI's; the channel's window may make it wait) val copy = data.copyOfRange(offset, offset + length) return try { - io.execute { - try { - synchronized(o) { - o.write(copy) - o.flush() - } - } catch (_: IOException) { - } - } + io.execute { write(shell, x, copy, 0, copy.size) } true } catch (_: java.util.concurrent.RejectedExecutionException) { false @@ -298,29 +457,21 @@ class SshLink( override fun resize(cols: Int, rows: Int) { this.cols = cols this.rows = rows - val sh = shell ?: return + val x = shellHandler ?: return try { io.execute { - try { - sh.changeWindowDimensions(cols, rows, 0, 0) - } catch (_: Exception) { - } + synchronized(lock) { if (h != 0L && handlers[shell] === x) NativeSsh.resize(h, shell, cols, rows) } } } catch (_: java.util.concurrent.RejectedExecutionException) { } } - /** the shell closed and the link with it, on a thread of its own; no reason given */ + /** the connection closed and the link with it; no reason given */ override fun close() { closing = true cancelAsks(this) - Thread({ - try { - shell?.close() - } catch (_: Exception) { - } - closed(null) - }, "ssh-$host-close").apply { isDaemon = true }.start() + synchronized(lock) { if (h != 0L) NativeSsh.disconnect(h) } + if (!started) closed(null) } companion object { diff --git a/app/src/main/java/org/dmodem/app/android/ssh/SshWire.kt b/app/src/main/java/org/dmodem/app/android/ssh/SshWire.kt new file mode 100644 index 0000000..48a7db4 --- /dev/null +++ b/app/src/main/java/org/dmodem/app/android/ssh/SshWire.kt @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package org.dmodem.app.android.ssh + +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.math.BigInteger +import java.security.AlgorithmParameters +import java.security.KeyFactory +import java.security.MessageDigest +import java.security.PublicKey +import java.security.interfaces.ECPublicKey +import java.security.interfaces.RSAPublicKey +import java.security.spec.ECGenParameterSpec +import java.security.spec.ECParameterSpec +import java.security.spec.ECPoint +import java.security.spec.ECPublicKeySpec +import java.security.spec.RSAPublicKeySpec +import java.security.spec.X509EncodedKeySpec +import java.util.Base64 + +/** SSH's wire encoding (RFC 4251): what's put, in order; [bytes] once done. */ +class SshWriter { + private val out = ByteArrayOutputStream() + + /** one byte */ + fun byte(b: Int) = apply { out.write(b) } + + /** a uint32, big-endian */ + fun uint32(v: Long) = apply { + out.write((v ushr 24).toInt() and 0xff) + out.write((v ushr 16).toInt() and 0xff) + out.write((v ushr 8).toInt() and 0xff) + out.write(v.toInt() and 0xff) + } + + /** bytes as they are, with no length */ + fun raw(b: ByteArray) = apply { out.write(b) } + + /** a string: its length, then its bytes */ + fun bytes(b: ByteArray) = apply { uint32(b.size.toLong()); out.write(b) } + + /** a string of text, in UTF-8 */ + fun string(s: String) = bytes(s.toByteArray()) + + /** an mpint: two's complement, big-endian, as short as it goes */ + fun mpint(v: BigInteger) = bytes(if (v.signum() == 0) ByteArray(0) else v.toByteArray()) + + /** what's been put so far */ + fun size() = out.size() + + /** what's been put */ + fun bytes(): ByteArray = out.toByteArray() +} + +/** SSH's wire encoding read back, from [b]: each read throws at its end. */ +class SshReader(private val b: ByteArray) { + private var at = 0 + + /** what's left to read */ + fun available() = b.size - at + + /** [n] bytes, as they are */ + fun raw(n: Int): ByteArray { + if (n < 0 || n > available()) throw IOException("the SSH data ends early") + return b.copyOfRange(at, at + n).also { at += n } + } + + /** one byte, 0 to 255 */ + fun byte(): Int = raw(1)[0].toInt() and 0xff + + /** a uint32 */ + fun uint32(): Long = raw(4).fold(0L) { v, x -> (v shl 8) or (x.toLong() and 0xff) } + + /** a uint32 that fits an Int */ + fun int(): Int = uint32().also { if (it > Int.MAX_VALUE) throw IOException("an SSH length too large") }.toInt() + + /** a string's bytes */ + fun bytes(): ByteArray = raw(int()) + + /** a string of text */ + fun string(): String = String(bytes()) + + /** an mpint */ + fun mpint(): BigInteger = bytes().let { if (it.isEmpty()) BigInteger.ZERO else BigInteger(it) } +} + +/** + * Public keys in SSH's form (RSA, ECDSA on NIST P-256/384/521, Ed25519), + * to and from JCA's; their authorized_keys lines and fingerprints + * (SHA256:..., as ssh-keygen -l). + */ +object KeyFormat { + /** X.509's prefix of an Ed25519 key, before its 32 bytes */ + private val ED25519_X509 = byteArrayOf(0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00) + + /** the NIST curve of [bits]: its SSH name and JCA's */ + fun curve(bits: Int): Pair = when (bits) { + 256 -> "nistp256" to "secp256r1" + 384 -> "nistp384" to "secp384r1" + 521 -> "nistp521" to "secp521r1" + else -> throw IOException("no ECDSA on a $bits-bit curve") + } + + /** the curve's parameters, by its JCA name */ + fun ecParams(jcaName: String): ECParameterSpec = + AlgorithmParameters.getInstance("EC").run { + init(ECGenParameterSpec(jcaName)) + getParameterSpec(ECParameterSpec::class.java) + } + + /** the key's SSH type: ssh-ed25519, ecdsa-sha2-nistp256, ssh-rsa... */ + fun type(k: PublicKey): String = when (k) { + is RSAPublicKey -> "ssh-rsa" + is ECPublicKey -> "ecdsa-sha2-" + curve(k.params.curve.field.fieldSize).first + else -> if (k.algorithm.equals("Ed25519", true) || k.algorithm.equals("EdDSA", true)) "ssh-ed25519" else throw IOException("no SSH form for ${k.algorithm} keys") + } + + /** an Ed25519 key's 32 bytes */ + fun ed25519(k: PublicKey): ByteArray = k.encoded.let { it.copyOfRange(it.size - 32, it.size) } + + /** an EC point, uncompressed, as SSH has it */ + fun point(k: ECPublicKey): ByteArray { + val n = (k.params.curve.field.fieldSize + 7) / 8 + /** [v] in exactly n bytes */ + fun fixed(v: BigInteger): ByteArray { + val b = v.toByteArray().let { if (it.size > n) it.copyOfRange(it.size - n, it.size) else it } + return ByteArray(n - b.size) + b + } + return byteArrayOf(4) + fixed(k.w.affineX) + fixed(k.w.affineY) + } + + /** the key in SSH's wire form (its type, then its fields) */ + fun blob(k: PublicKey): ByteArray { + val w = SshWriter().string(type(k)) + when (k) { + is RSAPublicKey -> w.mpint(k.publicExponent).mpint(k.modulus) + is ECPublicKey -> w.string(curve(k.params.curve.field.fieldSize).first).bytes(point(k)) + else -> w.bytes(ed25519(k)) + } + return w.bytes() + } + + /** the key's authorized_keys line: its type, its blob in base64, and [comment] if any */ + fun openSsh(k: PublicKey, comment: String = ""): String = + type(k) + " " + Base64.getEncoder().encodeToString(blob(k)) + if (comment.isNotEmpty()) " $comment" else "" + + /** the key's fingerprint, SHA256: and its blob's digest in unpadded base64 */ + fun fingerprint(k: PublicKey): String = fingerprint(blob(k)) + + /** a blob's fingerprint */ + fun fingerprint(blob: ByteArray): String = + "SHA256:" + Base64.getEncoder().withoutPadding().encodeToString(MessageDigest.getInstance("SHA-256").digest(blob)) + + /** a public key from its blob */ + fun fromBlob(blob: ByteArray): PublicKey = read(SshReader(blob)) + + /** a public key read from [r]: its type, then its fields */ + fun read(r: SshReader): PublicKey { + val type = r.string() + return when { + type == "ssh-rsa" -> { + val e = r.mpint() + val n = r.mpint() + KeyFactory.getInstance("RSA").generatePublic(RSAPublicKeySpec(n, e)) + } + type.startsWith("ecdsa-sha2-") -> ecPublic(r.string(), r.bytes()) + type == "ssh-ed25519" -> ed25519Public(r.bytes()) + else -> throw IOException("unknown key type $type") + } + } + + /** an Ed25519 public key from its 32 bytes */ + fun ed25519Public(raw: ByteArray): PublicKey { + if (raw.size != 32) throw IOException("an Ed25519 key is 32 bytes") + SshSecurity.ensure() + return KeyFactory.getInstance("Ed25519", "BC").generatePublic(X509EncodedKeySpec(ED25519_X509 + raw)) + } + + /** an ECDSA public key from its curve's SSH name and its point (uncompressed) */ + fun ecPublic(curveName: String, q: ByteArray): PublicKey { + val jca = when (curveName) { + "nistp256" -> "secp256r1" + "nistp384" -> "secp384r1" + "nistp521" -> "secp521r1" + else -> throw IOException("unknown curve $curveName") + } + val params = ecParams(jca) + val n = (params.curve.field.fieldSize + 7) / 8 + if (q.size != 1 + 2 * n || q[0] != 4.toByte()) throw IOException("not an uncompressed EC point") + val x = BigInteger(1, q.copyOfRange(1, 1 + n)) + val y = BigInteger(1, q.copyOfRange(1 + n, q.size)) + return KeyFactory.getInstance("EC").generatePublic(ECPublicKeySpec(ECPoint(x, y), params)) + } +} diff --git a/app/src/main/java/org/dmodem/app/android/terminal/Terminal.kt b/app/src/main/java/org/dmodem/app/android/terminal/Terminal.kt index ccc0462..816eb8e 100644 --- a/app/src/main/java/org/dmodem/app/android/terminal/Terminal.kt +++ b/app/src/main/java/org/dmodem/app/android/terminal/Terminal.kt @@ -111,7 +111,7 @@ object Terminal { EntryKind.SSH -> { val key = if (e.auth == SshAuth.KEY) { try { - keys.provider(e.keyId) + keys.privateText(e.keyId) } catch (x: Exception) { return "the key can't be opened: ${x.message}" } diff --git a/app/src/test/java/org/dmodem/app/android/ssh/OpenSshInteropTest.kt b/app/src/test/java/org/dmodem/app/android/ssh/OpenSshInteropTest.kt index ecc7124..607a609 100644 --- a/app/src/test/java/org/dmodem/app/android/ssh/OpenSshInteropTest.kt +++ b/app/src/test/java/org/dmodem/app/android/ssh/OpenSshInteropTest.kt @@ -127,7 +127,7 @@ class OpenSshInteropTest { ): SshLink { val known = KnownHosts(tmp.newFile()) { _, _ -> Answer(accepted = true) } val l = SshLink( - "127.0.0.1", port, System.getProperty("user.name"), keys.provider(k.id), known, + "127.0.0.1", port, System.getProperty("user.name"), keys.privateText(k.id), known, ask = { _, _ -> asked.incrementAndGet(); Answer() }, forwardSpecs = forwards, agent = agent, ) diff --git a/app/src/test/java/org/dmodem/app/android/ssh/SshLinkTest.kt b/app/src/test/java/org/dmodem/app/android/ssh/SshLinkTest.kt index 1696f6a..393bd6d 100644 --- a/app/src/test/java/org/dmodem/app/android/ssh/SshLinkTest.kt +++ b/app/src/test/java/org/dmodem/app/android/ssh/SshLinkTest.kt @@ -151,7 +151,7 @@ class SshLinkTest { user: String, ask: (Prompt, Any?) -> Answer, known: KnownHosts, - key: net.schmizz.sshj.userauth.keyprovider.KeyProvider? = null, + key: String? = null, saved: String? = null, kept: MutableList = mutableListOf(), ) = SshLink("127.0.0.1", server.port, user, key, known, ask, savedPassword = saved, keepPassword = { kept.add(it) }, cols = 100, rows = 30) @@ -265,7 +265,7 @@ class SshLinkTest { allowedKeys.add(keys.keyPair(k.id).public) val known = KnownHosts(tmp.newFile("known_hosts_${kind.name}")) { p, o -> user()(p, o) } prompts.clear() - val l = link("bob", user(), known, key = keys.provider(k.id)) + val l = link("bob", user(), known, key = keys.privateText(k.id)) val screen = Screen() l.addListener(screen) l.connect() @@ -301,7 +301,7 @@ class SshLinkTest { // and they log in allowedKeys.add(pair.public) val known = KnownHosts(tmp.newFile("known_hosts")) { p, o -> user()(p, o) } - val l = link("bob", user(), known, key = keys.provider(k1.id)) + val l = link("bob", user(), known, key = keys.privateText(k1.id)) val screen = Screen() l.addListener(screen) l.connect() diff --git a/docs/building.md b/docs/building.md index 883aebe..9e4c8f9 100644 --- a/docs/building.md +++ b/docs/building.md @@ -8,7 +8,10 @@ You need JDK 17 or later and the Android SDK with platform 37, NDK 29.0.14206865 and CMake 3.31.6 (`sdkmanager "platforms;android-37.0" "ndk;29.0.14206865" "cmake;3.31.6"`). D-Modem's CMake fetches libre and Mbed TLS (git) while configuring and builds them with the NDK's toolchain -for each ABI. `./gradlew connectedDebugAndroidTest` runs the instrumented +for each ABI; the SSH client (`native-ssh`) fetches libssh's and its own +Mbed TLS's release tarballs (pinned by SHA-256) the same way. The unit +tests build that SSH client for the build host too (`buildHostSsh`: CMake, +a C compiler and the JDK's JNI headers). `./gradlew connectedDebugAndroidTest` runs the instrumented tests on a device or emulator (the native library loads and answers AT commands). diff --git a/docs/features.md b/docs/features.md index 169dec1..b314472 100644 --- a/docs/features.md +++ b/docs/features.md @@ -158,10 +158,21 @@ modem, in a terminal session of its own. On Android a directory entry connects by SSH, Telnet or rlogin (rlogin: the user's name sent as both names, the window's size when the server asks). On iOS the Terminal - tab's network button opens the Remote screen: SSH (a password login on - SwiftNIO SSH, `ios/DModemSSH`; the server's key kept the first time - it's trusted; Ed25519 and ECDSA host keys), Telnet or rlogin. Telnet - and rlogin are the shared Kotlin's (`org.dmodem.app.net`). + tab's network button opens the Remote screen: SSH (the server's key + kept the first time it's trusted), Telnet or rlogin. Telnet and rlogin + are the shared Kotlin's (`org.dmodem.app.net`). +- **SSH** is the same client on every platform, the GUI's on Linux, + Windows and macOS too: libdmodemssh (`native-ssh`), on libssh 0.11 and + its own Mbed TLS (both built from their release tarballs, pinned by + SHA-256). Android loads it through JNI (`NativeSsh.kt`), iOS as the + `DModemSSHNative` XCFramework (`ios/DModemSSH`). Ed25519, ECDSA and RSA + keys, the host's and the user's; password, keyboard-interactive and + key logins; on Android the app's own keys (made here, or OpenSSH's, + PEM or PuTTY's .ppk imported), port forwards (-L, -R, -D: SOCKS 4/4a/5) + and agent forwarding (-A, each signature asked of the user when the + entry says). Its tests run against a real sshd: `native-ssh/test`, + and the app's JVM tests on a host build of the JNI library + (`./gradlew :app:buildHostSsh`, run by the unit tests). - **Log**: the modem's and SIP's log (Copy for all of it). - **AT commands** (Settings, AT commands, and the terminal's menu): the AT command reference, D-Modem's manual (`docs/at_commands.pdf`, the diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 9246e2e..6ca8af8 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -11,7 +11,6 @@ junit = "4.13.2" coroutines = "1.10.2" atomicfu = "0.33.0" robolectric = "4.17" -sshj = "0.41.2" xz = "1.10" bouncycastle = "1.86" mina-sshd = "2.20.0" @@ -38,7 +37,6 @@ junit = { module = "junit:junit", version.ref = "junit" } kotlinx-atomicfu = { module = "org.jetbrains.kotlinx:atomicfu", version.ref = "atomicfu" } kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" } -sshj = { module = "com.hierynomus:sshj", version.ref = "sshj" } xz = { module = "org.tukaani:xz", version.ref = "xz" } bcprov = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" } bcpkix = { module = "org.bouncycastle:bcpkix-jdk18on", version.ref = "bouncycastle" } diff --git a/ios/DModem/Sources/RemoteModel.swift b/ios/DModem/Sources/RemoteModel.swift index 121b93f..e0bd5c5 100644 --- a/ios/DModem/Sources/RemoteModel.swift +++ b/ios/DModem/Sources/RemoteModel.swift @@ -7,7 +7,7 @@ import Foundation import Network /// A login to a server by SSH, Telnet or rlogin, in a terminal of its own -/// (beside the modem's). SSH is DModemSSH's (SwiftNIO SSH), its host keys +/// (beside the modem's). SSH is DModemSSH's (libdmodemssh, on libssh), its host keys /// kept here the first time they're accepted; Telnet and rlogin a TCP /// connection (Network) with the shared Kotlin's protocol (LoginBridge). @MainActor diff --git a/native-ssh/CMakeLists.txt b/native-ssh/CMakeLists.txt index 07929d2..3a5ec1d 100644 --- a/native-ssh/CMakeLists.txt +++ b/native-ssh/CMakeLists.txt @@ -24,6 +24,27 @@ if(NOT WIN32) endif() target_compile_options(dmodemssh PRIVATE -Wall -Wextra -Wshadow) +# the Android app's JNI library (NativeSsh.kt): in the app, and on the +# build host for its JVM tests (-DDMODEM_SSH_JNI=ON) +option(DMODEM_SSH_JNI "Build libdmodem_ssh_jni" ${ANDROID}) +if(DMODEM_SSH_JNI) + add_library(dmodem_ssh_jni SHARED jni/ssh_jni.c) + target_link_libraries(dmodem_ssh_jni PRIVATE dmodemssh) + if(NOT ANDROID) + find_package(JNI REQUIRED) + target_include_directories(dmodem_ssh_jni PRIVATE ${JNI_INCLUDE_DIRS}) + endif() + # (only Java's entry points seen: libssh's and mbedTLS's kept inside) + set_target_properties(dmodem_ssh_jni PROPERTIES C_VISIBILITY_PRESET hidden) + if(NOT APPLE) + target_link_options(dmodem_ssh_jni PRIVATE -Wl,--exclude-libs,ALL) + endif() + if(ANDROID) + # 16 KB pages (Android 15 on) + target_link_options(dmodem_ssh_jni PRIVATE -Wl,-z,max-page-size=16384 -Wl,--gc-sections) + endif() +endif() + if(NOT ANDROID AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS") enable_testing() add_executable(dmodemssh_test test/dmodemssh_test.c) diff --git a/native-ssh/cmake/BundledLibssh.cmake b/native-ssh/cmake/BundledLibssh.cmake index 83e5970..7984c56 100644 --- a/native-ssh/cmake/BundledLibssh.cmake +++ b/native-ssh/cmake/BundledLibssh.cmake @@ -63,16 +63,19 @@ if(ANDROID) list(APPEND _ssh_args -DCMAKE_C_FLAGS=-DS_IWRITE=S_IWUSR) endif() +# (WITH_SERVER: libssh runs a client's callbacks for the channels the +# server opens, the forwarded agent's, only when it's built with it) ExternalProject_Add(dmodem_libssh_build URL ${DMODEM_LIBSSH_URL} URL_HASH SHA256=${DMODEM_LIBSSH_SHA256} DOWNLOAD_EXTRACT_TIMESTAMP TRUE DEPENDS dmodem_mbedtls + PATCH_COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_LIST_DIR}/PatchLibssh.cmake LIST_SEPARATOR | CMAKE_ARGS ${_args} ${_ssh_args} -DBUILD_SHARED_LIBS=OFF -DWITH_MBEDTLS=ON -DMBEDTLS_ROOT_DIR=${_prefix} -DCMAKE_PREFIX_PATH=${_prefix} -DCMAKE_FIND_ROOT_PATH=${_prefix} - -DWITH_ZLIB=OFF -DWITH_GSSAPI=OFF -DWITH_SERVER=OFF + -DWITH_ZLIB=OFF -DWITH_GSSAPI=OFF -DWITH_SERVER=ON -DWITH_EXAMPLES=OFF -DUNIT_TESTING=OFF -DCLIENT_TESTING=OFF -DWITH_NACL=OFF -DWITH_SYMBOL_VERSIONING=OFF BUILD_BYPRODUCTS ${_prefix}/lib/${_ssh_lib}) diff --git a/native-ssh/cmake/PatchLibssh.cmake b/native-ssh/cmake/PatchLibssh.cmake new file mode 100644 index 0000000..c08b7a5 --- /dev/null +++ b/native-ssh/cmake/PatchLibssh.cmake @@ -0,0 +1,49 @@ +# libssh's remote listen on port 0 told the port the server picked from +# its own reply: libssh reads it from whatever packet came in last, which +# is often another one (its own "FIXME"), and then fails a listen that +# the server took. The reply's port kept in the session as it comes. +# Run in libssh's source tree by BundledLibssh.cmake. + +# (a replace that must take: else this libssh isn't the one patched for) +function(dmodem_patch file from to) + file(READ ${file} _text) + string(FIND "${_text}" "${to}" _done) + if(_done GREATER -1) + return() + endif() + string(FIND "${_text}" "${from}" _at) + if(_at LESS 0) + message(FATAL_ERROR "PatchLibssh: ${file} isn't as expected") + endif() + string(REPLACE "${from}" "${to}" _text "${_text}") + file(WRITE ${file} "${_text}") +endfunction() + +dmodem_patch(include/libssh/session.h + " enum ssh_channel_request_state_e global_req_state;" + " enum ssh_channel_request_state_e global_req_state; + /* D-Modem: bound port, from a global request's success */ + int dmodem_bound_port;") + +dmodem_patch(src/channels.c + " } else { + session->global_req_state=SSH_CHANNEL_REQ_STATE_ACCEPTED; + }" + " } else { + /* D-Modem: bound port */ + uint32_t bound = 0; + session->global_req_state=SSH_CHANNEL_REQ_STATE_ACCEPTED; + session->dmodem_bound_port = + ssh_buffer_unpack(packet, \"d\", &bound) == SSH_OK ? (int)bound : 0; + }") + +dmodem_patch(src/channels.c + " if (rc == SSH_OK && port == 0 && bound_port != NULL) { + rc = ssh_buffer_unpack(session->in_buffer, \"d\", bound_port); + if (rc != SSH_OK) + *bound_port = 0; + }" + " if (rc == SSH_OK && port == 0 && bound_port != NULL) { + /* D-Modem: bound port, as the success packet had it */ + *bound_port = session->dmodem_bound_port; + }") diff --git a/native-ssh/include/dmodemssh.h b/native-ssh/include/dmodemssh.h index d202286..6868b2b 100644 --- a/native-ssh/include/dmodemssh.h +++ b/native-ssh/include/dmodemssh.h @@ -132,8 +132,8 @@ void dmc_ssh_answered(dmc_ssh *s); DMC_SSH_EV_OPEN tells whether it opened */ /* a shell on a pty of term in the given size; agent: ssh -A asked */ int dmc_ssh_shell(dmc_ssh *s, const char *term, int cols, int rows, int agent); -/* a command run, with no pty */ -int dmc_ssh_exec(dmc_ssh *s, const char *command); +/* a command run, with no pty; agent: ssh -A asked */ +int dmc_ssh_exec(dmc_ssh *s, const char *command, int agent); /* a TCP connection made from the server to host:port (ssh -L, -D), for a connection that came from from_host:from_port */ int dmc_ssh_direct(dmc_ssh *s, const char *host, int port, @@ -144,8 +144,9 @@ int dmc_ssh_direct(dmc_ssh *s, const char *host, int port, int dmc_ssh_listen(dmc_ssh *s, const char *address, int port); /* that listen stopped */ void dmc_ssh_unlisten(dmc_ssh *s, const char *address, int port); -/* data to a channel (kept until the server can take it): 0, or -1 if - the channel isn't open */ +/* data to a channel (kept until the server can take it): how many + bytes are still kept (0 when all went; len 0 asks), or -1 if the + channel isn't open */ int dmc_ssh_write(dmc_ssh *s, int channel, const char *data, int len); /* the channel's end of data sent */ void dmc_ssh_eof(dmc_ssh *s, int channel); diff --git a/native-ssh/jni/ssh_jni.c b/native-ssh/jni/ssh_jni.c new file mode 100644 index 0000000..3f719d4 --- /dev/null +++ b/native-ssh/jni/ssh_jni.c @@ -0,0 +1,289 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + * + * ssh_jni.c - libdmodemssh for the Android app: the JNI side of + * org.dmodem.app.android.ssh.NativeSsh (each dmc_ssh a long, + * strings as Java's, bytes as byte[]). + */ +#include +#include +#include +#include + +#include "dmodemssh.h" + +#define FN(name) Java_org_dmodem_app_android_ssh_NativeSsh_##name + +/* a Java string as UTF-8, to release with done(); NULL for null */ +static const char *str(JNIEnv *env, jstring s) +{ + return s ? (*env)->GetStringUTFChars(env, s, NULL) : NULL; +} + +/* str()'s string released */ +static void done(JNIEnv *env, jstring s, const char *c) +{ + if (s && c) + (*env)->ReleaseStringUTFChars(env, s, c); +} + +/* the handle as the connection */ +static dmc_ssh *S(jlong h) +{ + return (dmc_ssh *)(intptr_t)h; +} + +/* a C string (or NULL) as a Java string */ +static jstring jstr(JNIEnv *env, const char *s) +{ + return s ? (*env)->NewStringUTF(env, s) : NULL; +} + +/* bytes as a byte[] */ +static jbyteArray jbytes(JNIEnv *env, const char *p, int n) +{ + jbyteArray a = (*env)->NewByteArray(env, n); + if (a && n) + (*env)->SetByteArrayRegion(env, a, 0, n, (const jbyte *)p); + return a; +} + +/* NativeSsh.new: a connection, or 0 */ +JNIEXPORT jlong JNICALL FN(create)(JNIEnv *env, jclass c, jstring host, jint port, jstring user) +{ + const char *h = str(env, host), *u = str(env, user); + dmc_ssh *s = dmc_ssh_new(h, port, u); + (void)c; + done(env, host, h); + done(env, user, u); + return (jlong)(intptr_t)s; +} + +/* NativeSsh.free */ +JNIEXPORT void JNICALL FN(free)(JNIEnv *env, jclass c, jlong h) +{ + (void)env; + (void)c; + dmc_ssh_free(S(h)); +} + +/* NativeSsh.option: 0, or -1 */ +JNIEXPORT jint JNICALL FN(option)(JNIEnv *env, jclass c, jlong h, jstring name, jstring value) +{ + const char *n = str(env, name), *v = str(env, value); + int r = dmc_ssh_option(S(h), n, v ? v : ""); + (void)c; + done(env, name, n); + done(env, value, v); + return r; +} + +/* NativeSsh.poll: 1 with the event's type, channel and value in ev[0..2] + (its data returned: null if none), 0 on a timeout, -1 when over */ +JNIEXPORT jbyteArray JNICALL FN(poll)(JNIEnv *env, jclass c, jlong h, jint ms, jintArray ev) +{ + dmc_ssh_event e; + jint v[4] = { 0, 0, 0, 0 }; + int r = dmc_ssh_poll(S(h), ms, &e); + (void)c; + v[0] = r; + if (r == 1) { + v[1] = e.type; + v[2] = e.channel; + v[3] = e.value; + } + (*env)->SetIntArrayRegion(env, ev, 0, 4, v); + return r == 1 && e.data ? jbytes(env, e.data, e.len) : NULL; +} + +/* NativeSsh.disconnect */ +JNIEXPORT void JNICALL FN(disconnect)(JNIEnv *env, jclass c, jlong h) +{ + (void)env; + (void)c; + dmc_ssh_disconnect(S(h)); +} + +/* NativeSsh.trust */ +JNIEXPORT void JNICALL FN(trust)(JNIEnv *env, jclass c, jlong h, jboolean ok, jboolean remember) +{ + (void)env; + (void)c; + dmc_ssh_trust(S(h), ok, remember); +} + +/* NativeSsh.authPassword */ +JNIEXPORT void JNICALL FN(authPassword)(JNIEnv *env, jclass c, jlong h, jstring pw) +{ + const char *p = str(env, pw); + (void)c; + dmc_ssh_auth_password(S(h), p ? p : ""); + done(env, pw, p); +} + +/* NativeSsh.authKey: 0, or -1 if the key can't be read */ +JNIEXPORT jint JNICALL FN(authKey)(JNIEnv *env, jclass c, jlong h, jstring key, jstring pass) +{ + const char *k = str(env, key), *p = str(env, pass); + int r = dmc_ssh_auth_key(S(h), k, p); + (void)c; + done(env, key, k); + done(env, pass, p); + return r; +} + +/* NativeSsh.authInteractive */ +JNIEXPORT void JNICALL FN(authInteractive)(JNIEnv *env, jclass c, jlong h) +{ + (void)env; + (void)c; + dmc_ssh_auth_interactive(S(h)); +} + +/* NativeSsh.authCancel */ +JNIEXPORT void JNICALL FN(authCancel)(JNIEnv *env, jclass c, jlong h) +{ + (void)env; + (void)c; + dmc_ssh_auth_cancel(S(h)); +} + +/* NativeSsh.instruction */ +JNIEXPORT jstring JNICALL FN(instruction)(JNIEnv *env, jclass c, jlong h) +{ + (void)c; + return jstr(env, dmc_ssh_instruction(S(h))); +} + +/* NativeSsh.prompt: the question; echo[0] whether its answer may show */ +JNIEXPORT jstring JNICALL FN(prompt)(JNIEnv *env, jclass c, jlong h, jint i, jbooleanArray echo) +{ + int e = 0; + const char *q = dmc_ssh_prompt(S(h), i, &e); + jboolean b = e != 0; + (void)c; + if (echo) + (*env)->SetBooleanArrayRegion(env, echo, 0, 1, &b); + return jstr(env, q); +} + +/* NativeSsh.answer */ +JNIEXPORT void JNICALL FN(answer)(JNIEnv *env, jclass c, jlong h, jint i, jstring a) +{ + const char *s = str(env, a); + (void)c; + dmc_ssh_answer(S(h), i, s ? s : ""); + done(env, a, s); +} + +/* NativeSsh.answered */ +JNIEXPORT void JNICALL FN(answered)(JNIEnv *env, jclass c, jlong h) +{ + (void)env; + (void)c; + dmc_ssh_answered(S(h)); +} + +/* NativeSsh.shell: a channel, or -1 */ +JNIEXPORT jint JNICALL FN(shell)(JNIEnv *env, jclass c, jlong h, jstring term, jint cols, jint rows, jboolean agent) +{ + const char *t = str(env, term); + int r = dmc_ssh_shell(S(h), t, cols, rows, agent); + (void)c; + done(env, term, t); + return r; +} + +/* NativeSsh.exec: a channel, or -1 */ +JNIEXPORT jint JNICALL FN(exec)(JNIEnv *env, jclass c, jlong h, jstring cmd, jboolean agent) +{ + const char *t = str(env, cmd); + int r = dmc_ssh_exec(S(h), t, agent); + (void)c; + done(env, cmd, t); + return r; +} + +/* NativeSsh.direct: a channel, or -1 */ +JNIEXPORT jint JNICALL FN(direct)(JNIEnv *env, jclass c, jlong h, jstring host, jint port, jstring from, jint fromPort) +{ + const char *t = str(env, host), *f = str(env, from); + int r = dmc_ssh_direct(S(h), t, port, f, fromPort); + (void)c; + done(env, host, t); + done(env, from, f); + return r; +} + +/* NativeSsh.listen: a request's number, or -1 */ +JNIEXPORT jint JNICALL FN(listen)(JNIEnv *env, jclass c, jlong h, jstring addr, jint port) +{ + const char *a = str(env, addr); + int r = dmc_ssh_listen(S(h), a, port); + (void)c; + done(env, addr, a); + return r; +} + +/* NativeSsh.unlisten */ +JNIEXPORT void JNICALL FN(unlisten)(JNIEnv *env, jclass c, jlong h, jstring addr, jint port) +{ + const char *a = str(env, addr); + (void)c; + dmc_ssh_unlisten(S(h), a, port); + done(env, addr, a); +} + +/* NativeSsh.write: the bytes still kept for the server, or -1 if the channel isn't open */ +JNIEXPORT jint JNICALL FN(write)(JNIEnv *env, jclass c, jlong h, jint ch, jbyteArray data, jint off, jint len) +{ + jbyte *b = (*env)->GetByteArrayElements(env, data, NULL); + int r; + (void)c; + if (!b) + return -1; + r = dmc_ssh_write(S(h), ch, (const char *)b + off, len); + (*env)->ReleaseByteArrayElements(env, data, b, JNI_ABORT); + return r; +} + +/* NativeSsh.eof */ +JNIEXPORT void JNICALL FN(eof)(JNIEnv *env, jclass c, jlong h, jint ch) +{ + (void)env; + (void)c; + dmc_ssh_eof(S(h), ch); +} + +/* NativeSsh.close */ +JNIEXPORT void JNICALL FN(close)(JNIEnv *env, jclass c, jlong h, jint ch) +{ + (void)env; + (void)c; + dmc_ssh_close(S(h), ch); +} + +/* NativeSsh.resize */ +JNIEXPORT void JNICALL FN(resize)(JNIEnv *env, jclass c, jlong h, jint ch, jint cols, jint rows) +{ + (void)env; + (void)c; + dmc_ssh_resize(S(h), ch, cols, rows); +} + +/* NativeSsh.keyExport: the key in OpenSSH's form under a new passphrase, or null */ +JNIEXPORT jstring JNICALL FN(keyExport)(JNIEnv *env, jclass c, jstring key, jstring pass, jstring newPass) +{ + const char *k = str(env, key), *p = str(env, pass), *n = str(env, newPass); + char *out = NULL; + jstring r = NULL; + (void)c; + if (dmc_ssh_key_export(k, p, n, &out) == 0) + r = jstr(env, out); + dmc_ssh_free_string(out); + done(env, key, k); + done(env, pass, p); + done(env, newPass, n); + return r; +} diff --git a/native-ssh/src/dmodemssh.c b/native-ssh/src/dmodemssh.c index f05dc20..13ecea7 100644 --- a/native-ssh/src/dmodemssh.c +++ b/native-ssh/src/dmodemssh.c @@ -27,6 +27,7 @@ typedef CRITICAL_SECTION lock_t; #define LOCK_FREE(l) DeleteCriticalSection(l) #define LOCK(l) EnterCriticalSection(l) #define UNLOCK(l) LeaveCriticalSection(l) +/* ms milliseconds slept */ static void nap(int ms) { Sleep((DWORD)ms); } #else #include @@ -37,6 +38,7 @@ typedef pthread_mutex_t lock_t; #define LOCK_FREE(l) pthread_mutex_destroy(l) #define LOCK(l) pthread_mutex_lock(l) #define UNLOCK(l) pthread_mutex_unlock(l) +/* ms milliseconds slept */ static void nap(int ms) { struct timespec t = { ms / 1000, (long)(ms % 1000) * 1000000L }; @@ -289,6 +291,7 @@ static void init_once(void) } } +/* a connection to make to user@host:port (nothing done until polled) */ dmc_ssh *dmc_ssh_new(const char *host, int port, const char *user) { dmc_ssh *s; @@ -323,6 +326,7 @@ dmc_ssh *dmc_ssh_new(const char *host, int port, const char *user) return s; } +/* the connection dropped (if it's up) and freed */ void dmc_ssh_free(dmc_ssh *s) { int i; @@ -358,6 +362,11 @@ void dmc_ssh_free(dmc_ssh *s) free(s); } +/* an option, before the first poll: 0, or -1 if it's not one. "config" + OpenSSH's config read (a path; "" its own ~/.ssh/config) + "knownhosts" the host's key looked up there (a path; "" OpenSSH's) + "hostkeys" the host key algorithms, in order (a list with commas) + "timeout" seconds to connect in "compression" "yes" or "no" */ int dmc_ssh_option(dmc_ssh *s, const char *name, const char *value) { int r = -1; @@ -530,7 +539,7 @@ static void channel_step(dmc_ssh *s, int n) return; if (r != SSH_OK) goto refused; - c->step = c->command ? C_EXEC : c->agent ? C_AGENT : C_PTY; + c->step = c->agent ? C_AGENT : c->command ? C_EXEC : C_PTY; continue; case C_OPEN_DIRECT: r = ssh_channel_open_forward(c->ch, c->host, c->port, @@ -548,7 +557,7 @@ static void channel_step(dmc_ssh *s, int n) r = ssh_channel_request_auth_agent(c->ch); if (r == SSH_AGAIN) return; - c->step = C_PTY; + c->step = c->command ? C_EXEC : C_PTY; continue; case C_PTY: r = ssh_channel_request_pty_size(c->ch, c->term, c->cols, c->rows); @@ -824,6 +833,9 @@ static void wait_socket(socket_t fd, int ms) select((int)fd + 1, &r, NULL, NULL, &t); } +/* the next event: 1 (in *ev), 0 when timeout_ms passed with none, -1 + when the connection is over and its DMC_SSH_EV_CLOSED was handed + back */ int dmc_ssh_poll(dmc_ssh *s, int timeout_ms, dmc_ssh_event *ev) { int waited = 0; @@ -872,6 +884,8 @@ int dmc_ssh_poll(dmc_ssh *s, int timeout_ms, dmc_ssh_event *ev) } } +/* the connection closed by the user: a DMC_SSH_EV_CLOSED with NULL + comes */ void dmc_ssh_disconnect(dmc_ssh *s) { LOCK(&s->lock); @@ -882,6 +896,8 @@ void dmc_ssh_disconnect(dmc_ssh *s) /* -- the login -- */ +/* the server's key: trusted (ok) or not; remember: added to + known_hosts */ void dmc_ssh_trust(dmc_ssh *s, int ok, int remember) { LOCK(&s->lock); @@ -897,6 +913,7 @@ static void choose(dmc_ssh *s, int how) s->login = how; } +/* a login tried (an answer to DMC_SSH_EV_AUTH) */ void dmc_ssh_auth_password(dmc_ssh *s, const char *password) { LOCK(&s->lock); @@ -908,6 +925,8 @@ void dmc_ssh_auth_password(dmc_ssh *s, const char *password) UNLOCK(&s->lock); } +/* by a private key's text (OpenSSH's, PEM): 0, or -1 when it can't be + read with that passphrase (nothing is tried: answer again) */ int dmc_ssh_auth_key(dmc_ssh *s, const char *key, const char *passphrase) { ssh_key k = NULL; @@ -929,6 +948,7 @@ int dmc_ssh_auth_key(dmc_ssh *s, const char *key, const char *passphrase) return 0; } +/* by the system's agent (SSH_AUTH_SOCK) */ void dmc_ssh_auth_agent(dmc_ssh *s) { LOCK(&s->lock); @@ -936,6 +956,8 @@ void dmc_ssh_auth_agent(dmc_ssh *s) UNLOCK(&s->lock); } +/* as OpenSSH's ssh does: the agent, then ~/.ssh's keys with no + passphrase */ void dmc_ssh_auth_auto(dmc_ssh *s) { LOCK(&s->lock); @@ -943,6 +965,7 @@ void dmc_ssh_auth_auto(dmc_ssh *s) UNLOCK(&s->lock); } +/* by the server's questions (keyboard-interactive) */ void dmc_ssh_auth_interactive(dmc_ssh *s) { LOCK(&s->lock); @@ -950,6 +973,7 @@ void dmc_ssh_auth_interactive(dmc_ssh *s) UNLOCK(&s->lock); } +/* no more tries: the connection closes, "not logged in" */ void dmc_ssh_auth_cancel(dmc_ssh *s) { LOCK(&s->lock); @@ -958,6 +982,7 @@ void dmc_ssh_auth_cancel(dmc_ssh *s) UNLOCK(&s->lock); } +/* a DMC_SSH_EV_PROMPTS round's instruction */ const char *dmc_ssh_instruction(dmc_ssh *s) { const char *r; @@ -968,6 +993,8 @@ const char *dmc_ssh_instruction(dmc_ssh *s) return r ? r : ""; } +/* a DMC_SSH_EV_PROMPTS round: its instruction, and question i (*echo: + whether the answer may be shown) */ const char *dmc_ssh_prompt(dmc_ssh *s, int i, int *echo) { const char *r = NULL; @@ -982,6 +1009,7 @@ const char *dmc_ssh_prompt(dmc_ssh *s, int i, int *echo) return r ? r : ""; } +/* question i's answer, for the round's dmc_ssh_answered() */ void dmc_ssh_answer(dmc_ssh *s, int i, const char *answer) { LOCK(&s->lock); @@ -990,6 +1018,7 @@ void dmc_ssh_answer(dmc_ssh *s, int i, const char *answer) UNLOCK(&s->lock); } +/* the round's answers sent */ void dmc_ssh_answered(dmc_ssh *s) { LOCK(&s->lock); @@ -1000,6 +1029,7 @@ void dmc_ssh_answered(dmc_ssh *s) /* -- channels -- */ +/* a shell on a pty of term in the given size; agent: ssh -A asked */ int dmc_ssh_shell(dmc_ssh *s, const char *term, int cols, int rows, int agent) { int n; @@ -1018,7 +1048,8 @@ int dmc_ssh_shell(dmc_ssh *s, const char *term, int cols, int rows, int agent) return n; } -int dmc_ssh_exec(dmc_ssh *s, const char *command) +/* a command run, with no pty; agent: ssh -A asked */ +int dmc_ssh_exec(dmc_ssh *s, const char *command, int agent) { int n; @@ -1026,12 +1057,15 @@ int dmc_ssh_exec(dmc_ssh *s, const char *command) n = new_slot(s); if (n > 0) { s->ch[n - 1].command = copy(command); + s->ch[n - 1].agent = agent; s->ch[n - 1].step = C_OPEN_SESSION; } UNLOCK(&s->lock); return n; } +/* a TCP connection made from the server to host:port (ssh -L, -D), for + a connection that came from from_host:from_port */ int dmc_ssh_direct(dmc_ssh *s, const char *host, int port, const char *from_host, int from_port) { @@ -1051,6 +1085,9 @@ int dmc_ssh_direct(dmc_ssh *s, const char *host, int port, return n; } +/* the server asked to listen on address:port (ssh -R; NULL: its + default, 0: a port it picks): a request's number, answered by a + DMC_SSH_EV_LISTEN; its connections come as DMC_SSH_EV_INCOMING */ int dmc_ssh_listen(dmc_ssh *s, const char *address, int port) { int i, id = -1; @@ -1072,6 +1109,7 @@ int dmc_ssh_listen(dmc_ssh *s, const char *address, int port) return id; } +/* that listen stopped */ void dmc_ssh_unlisten(dmc_ssh *s, const char *address, int port) { int i; @@ -1096,6 +1134,9 @@ void dmc_ssh_unlisten(dmc_ssh *s, const char *address, int port) UNLOCK(&s->lock); } +/* data to a channel (kept until the server can take it): how many + bytes are still kept (0 when all went; len 0 asks), or -1 if the + channel isn't open */ int dmc_ssh_write(dmc_ssh *s, int channel, const char *data, int len) { chan_t *c; @@ -1106,12 +1147,13 @@ int dmc_ssh_write(dmc_ssh *s, int channel, const char *data, int len) if (c && c->step == C_OPEN && !c->eof_out && s->step == S_READY && buf_add(&c->out, data, len) == 0) { channel_flush(s, c); - r = 0; + r = c->out.len; } UNLOCK(&s->lock); return r; } +/* the channel's end of data sent */ void dmc_ssh_eof(dmc_ssh *s, int channel) { chan_t *c; @@ -1125,6 +1167,7 @@ void dmc_ssh_eof(dmc_ssh *s, int channel) UNLOCK(&s->lock); } +/* the channel closed (a DMC_SSH_EV_CLOSE comes) */ void dmc_ssh_close(dmc_ssh *s, int channel) { chan_t *c; @@ -1140,6 +1183,7 @@ void dmc_ssh_close(dmc_ssh *s, int channel) UNLOCK(&s->lock); } +/* a shell's pty resized */ void dmc_ssh_resize(dmc_ssh *s, int channel, int cols, int rows) { chan_t *c; @@ -1174,6 +1218,8 @@ static char *pub_line(ssh_key k) return r; } +/* OpenSSH's SHA256 fingerprint of a key's OpenSSH line ("SHA256:..."), + into buf: 0, or -1 if it isn't a key */ int dmc_ssh_fingerprint(const char *keyline, char *buf, int max) { char type[64], *b64; @@ -1224,6 +1270,10 @@ static int export_key(ssh_key k, const char *passphrase, char **out) return *out ? 0 : -1; } +/* a new key ("ed25519", "ecdsa" with bits 256, 384 or 521, "rsa" with + bits): its private text (OpenSSH's, encrypted with passphrase unless + it's NULL or "") and its public line, both to free with + dmc_ssh_free_string(): 0, or -1 */ int dmc_ssh_keygen(const char *type, int bits, const char *passphrase, char **private_key, char **public_key) { @@ -1260,6 +1310,8 @@ int dmc_ssh_keygen(const char *type, int bits, const char *passphrase, return r; } +/* a private key's public line: 0, or -1 if it can't be read with that + passphrase */ int dmc_ssh_key_public(const char *key, const char *passphrase, char **public_key) { ssh_key k = NULL; @@ -1274,6 +1326,8 @@ int dmc_ssh_key_public(const char *key, const char *passphrase, char **public_ke return *public_key ? 0 : -1; } +/* a private key written again (OpenSSH's form) with a new passphrase + (NULL or "": none): 0, or -1 */ int dmc_ssh_key_export(const char *key, const char *passphrase, const char *new_passphrase, char **out) { @@ -1290,6 +1344,7 @@ int dmc_ssh_key_export(const char *key, const char *passphrase, return r; } +/* a string these functions gave, freed */ void dmc_ssh_free_string(char *str) { free(str); diff --git a/native-ssh/test/dmodemssh_test.c b/native-ssh/test/dmodemssh_test.c index ab7c9b3..7259d6b 100644 --- a/native-ssh/test/dmodemssh_test.c +++ b/native-ssh/test/dmodemssh_test.c @@ -143,7 +143,7 @@ static void test_shell(dmc_ssh *s) CHECK(ch > 0); CHECK(next(s, &ev) == DMC_SSH_EV_OPEN && ev.channel == ch && ev.value == 1); - CHECK(dmc_ssh_write(s, ch, typed, (int)strlen(typed)) == 0); + CHECK(dmc_ssh_write(s, ch, typed, (int)strlen(typed)) >= 0); CHECK(drain(s, ch, out, sizeof out) == 3); CHECK(strstr(out, "30 100") != NULL); CHECK(strstr(out, "vt100") != NULL); @@ -155,11 +155,11 @@ static void test_exec(dmc_ssh *s) { dmc_ssh_event ev; char out[8192]; - int ch = dmc_ssh_exec(s, "tr a-z A-Z; exit 7"); + int ch = dmc_ssh_exec(s, "tr a-z A-Z; exit 7", 0); CHECK(ch > 0); CHECK(next(s, &ev) == DMC_SSH_EV_OPEN && ev.value == 1); - CHECK(dmc_ssh_write(s, ch, "hello\n", 6) == 0); + CHECK(dmc_ssh_write(s, ch, "hello\n", 6) >= 0); dmc_ssh_eof(s, ch); CHECK(drain(s, ch, out, sizeof out) == 7); CHECK(!strcmp(out, "HELLO\n")); @@ -211,7 +211,7 @@ static void test_listen(dmc_ssh *s) } while (t && t != DMC_SSH_EV_DATA); CHECK(t == DMC_SSH_EV_DATA && ev.channel == ch && ev.len == 4 && !memcmp(ev.data, "ping", 4)); - CHECK(dmc_ssh_write(s, ch, "pong", 4) == 0); + CHECK(dmc_ssh_write(s, ch, "pong", 4) >= 0); { /* (the reply comes as the session is polled) */ int got = 0, i; @@ -336,6 +336,7 @@ static void test_live(const char *spec) test_key_login(key); } +/* the key tests, then the live ones when DMODEM_SSH_TEST names a server */ int main(void) { const char *spec = getenv("DMODEM_SSH_TEST");