Merge pull request #48 from D-Modem/claude/project-thread-eywog3

SSH on libssh for iOS and Android (sshj and SwiftNIO SSH gone)
This commit is contained in:
Neo authored and GitHub committed 2026-11-12 06:30:46 -08:00
commit 48bf218a07
36 files changed
+3970 -888

No files matched your search

+19 -4
View File
@@ -234,10 +234,25 @@ jobs:
env:
DMODEM_HOST_BUILD: ${{ github.workspace }}/build-host
# the iOS app's SSH client (SwiftNIO SSH); its login tests run when
# DMODEM_SSH_TEST names an sshd (host:port:user:password), else skip
- name: DModemSSH (Swift)
run: swift test --package-path ios/DModemSSH
# the apps' SSH client (native-ssh: libdmodemssh on libssh), and the
# iOS app's Swift on it, against a real sshd
- name: SSH client
run: |
cmake -S native-ssh -B build-ssh -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build-ssh
sudo apt-get install -y --no-install-recommends openssh-server
sudo useradd -m dmtest
echo 'dmtest:Sesame-42' | sudo chpasswd
ssh-keygen -q -t ed25519 -N '' -f "$RUNNER_TEMP/key"
sudo install -d -m 700 -o dmtest ~dmtest/.ssh
sudo install -m 600 -o dmtest "$RUNNER_TEMP/key.pub" ~dmtest/.ssh/authorized_keys
sudo mkdir -p /run/sshd
sudo /usr/sbin/sshd -p 2222 -o ListenAddress=127.0.0.1 -o PasswordAuthentication=yes
DMODEM_SSH_TEST_KEY="$RUNNER_TEMP/key" build-ssh/dmodemssh_test
swift test --package-path ios/DModemSSH
env:
DMODEM_SSH_TEST: 127.0.0.1:2222:dmtest:Sesame-42
DMODEM_SSH_HOST_BUILD: ${{ github.workspace }}/build-ssh
# (Apple's ways on Linux: the portable fallbacks the iOS build has)
- name: Engine test, Apple's fallbacks
+2
View File
@@ -9,6 +9,8 @@ build/
captures/
# host builds of native-test
/build-host*/
# host builds of native-ssh
/build-ssh*/
.kotlin/
/build-apple/
/build-fallback/
+23 -6
View File
@@ -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<Exec>("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=<a Maven mirror> to fetch them elsewhere
tasks.withType<Test>().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") }
}
+2 -2
View File
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<!-- BouncyCastle's PKIX jar has trust managers for its own tools (EST); the app never uses them:
SSH checks host keys itself (known hosts) -->
<!-- BouncyCastle's PKIX jar (the SSH tests' PEM writer) has trust managers for its own tools
(EST); the app never uses them: SSH checks host keys itself (known hosts) -->
<issue id="TrustAllX509TrustManager">
<ignore path="**/bcpkix-jdk18on-*.jar" />
</issue>
+5 -4
View File
@@ -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 <methods>; }
# 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.** { *; }
+4
View File
@@ -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()
@@ -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"
}
}
@@ -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<ByteArray>()
/** whether the channel opened, once it's known */
val open = java.util.concurrent.CompletableFuture<Boolean>()
/** 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<List<ForwardState>> = MutableStateFlow(emptyList()),
private val log: (String) -> Unit = {},
) : Closeable {
@@ -138,6 +266,8 @@ class Forwards(
val states: StateFlow<List<ForwardState>> = _states.asStateFlow()
private val running = HashMap<ForwardSpec, Closeable>()
/** the remote forwards by the port the server bound */
private val remotes = java.util.concurrent.ConcurrentHashMap<Int, ForwardSpec>()
@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) {
}
}
}
}
@@ -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<KeyPair, String> {
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("'", "")
@@ -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) {
@@ -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<String> =
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<String> {
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",
)
}
}
@@ -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?
}
@@ -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<ByteArray, ByteArray, ByteArray> {
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<KeyPair, String> {
val lines = text.lines().map { it.trimEnd('\r') }
val head = mutableMapOf<String, String>()
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 */
@@ -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
}
}
@@ -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<ForwardSpec> = 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>(TerminalLink.State.Connecting)
override val state: StateFlow<TerminalLink.State> = _state.asStateFlow()
private val listeners = CopyOnWriteArrayList<TerminalLink.Listener>()
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<Int, ChannelHandler>()
/** channels whose number was taken again before their close was handed over: those closes to ignore */
private val staleCloses = HashMap<Int, Int>()
private val listens = HashMap<Int, (Int, String?) -> 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<List<String>> = _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<ChannelHandler>
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<String> =
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<String> = 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<AuthMethod> = 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<Int?, String>? {
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 {
@@ -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<String, String> = 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))
}
}
@@ -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}"
}
@@ -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,
)
@@ -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<String> = 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()
+4 -1
View File
@@ -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).
+15 -4
View File
@@ -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
-2
View File
@@ -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" }
+1 -1
View File
@@ -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
-68
View File
@@ -1,68 +0,0 @@
{
"pins" : [
{
"identity" : "swift-asn1",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-asn1.git",
"state" : {
"revision" : "917b472dbe53ba699cbb0495f9a95a084bc6364d",
"version" : "1.7.4"
}
},
{
"identity" : "swift-atomics",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-atomics.git",
"state" : {
"revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34",
"version" : "1.3.1"
}
},
{
"identity" : "swift-collections",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-collections.git",
"state" : {
"revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a",
"version" : "1.6.0"
}
},
{
"identity" : "swift-crypto",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-crypto.git",
"state" : {
"revision" : "da9d28d69ebe3894b18376c8f2395c2f37b8448f",
"version" : "4.5.2"
}
},
{
"identity" : "swift-nio",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio.git",
"state" : {
"revision" : "2f58d8ef84438d6517fc78bcea2f8527e3c72936",
"version" : "2.105.0"
}
},
{
"identity" : "swift-nio-ssh",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-ssh.git",
"state" : {
"revision" : "d1985926494b624e751b379009dc83f3395fd88a",
"version" : "0.15.1"
}
},
{
"identity" : "swift-system",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-system.git",
"state" : {
"revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750",
"version" : "1.8.1"
}
}
],
"version" : 2
}
+22 -11
View File
@@ -3,24 +3,35 @@
// Copyright (C) 2026 Neo-Desktop
//
// DModemSSH: the iOS app's SSH client, an interactive shell on a pty, on
// Apple's SwiftNIO SSH. Apart from the app so that it builds and its tests
// run on Linux too (against a local sshd, when DMODEM_SSH_TEST names one).
// libdmodemssh (native-ssh: the same engine as the Android and desktop
// apps', on libssh). On Apple's systems that is build-apple's XCFramework
// (ios/build-native.sh); on Linux the host build's libraries (cmake -S
// native-ssh -B build-ssh, or DMODEM_SSH_HOST_BUILD), so that its tests
// run there too (against a local sshd, when DMODEM_SSH_TEST names one).
import Foundation
import PackageDescription
#if os(Linux)
let host = ProcessInfo.processInfo.environment["DMODEM_SSH_HOST_BUILD"] ?? "../../build-ssh"
let native: Target = .systemLibrary(name: "CDModemSSH", path: "Sources/CDModemSSHHost")
let nativeLinking: [LinkerSetting] = [
.unsafeFlags(["-L\(host)", "-L\(host)/dmodem-libssh/lib"]),
.linkedLibrary("dmodemssh"), .linkedLibrary("ssh"),
.linkedLibrary("mbedtls"), .linkedLibrary("mbedx509"), .linkedLibrary("mbedcrypto"),
.linkedLibrary("everest"), .linkedLibrary("p256m"), .linkedLibrary("pthread"),
]
#else
let native: Target = .binaryTarget(name: "CDModemSSH", path: "../../build-apple/DModemSSHNative.xcframework")
let nativeLinking: [LinkerSetting] = []
#endif
let package = Package(
name: "DModemSSH",
platforms: [.macOS(.v12), .iOS(.v15)],
products: [.library(name: "DModemSSH", targets: ["DModemSSH"])],
dependencies: [
.package(url: "https://github.com/apple/swift-nio.git", from: "2.65.0"),
.package(url: "https://github.com/apple/swift-nio-ssh.git", from: "0.9.0"),
],
targets: [
.target(name: "DModemSSH", dependencies: [
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOPosix", package: "swift-nio"),
.product(name: "NIOSSH", package: "swift-nio-ssh"),
]),
native,
.target(name: "DModemSSH", dependencies: ["CDModemSSH"], linkerSettings: nativeLinking),
.testTarget(name: "DModemSSHTests", dependencies: ["DModemSSH"]),
]
)
@@ -0,0 +1,4 @@
module CDModemSSH [system] {
header "../../../../native-ssh/include/dmodemssh.h"
export *
}
+145 -251
View File
@@ -1,21 +1,21 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import CDModemSSH
import Foundation
import NIOCore
import NIOPosix
import NIOSSH
/// An SSH login's interactive shell: the host's key checked by the caller
/// ([verifyHostKey], its OpenSSH form), the user logged in by password
/// ([askPassword], asked again when one is refused, three times at most),
/// a pty of [term] in the screen's size and a shell on it. What the
/// server says (stdout and stderr) goes to [onData]; [write] sends what
/// is typed; [resize] the window's new size. [onClose] once, with why
/// (nil when it was asked to).
/// An SSH login's interactive shell, on libdmodemssh (native-ssh, on
/// libssh): the host's key checked by the caller ([verifyHostKey], its
/// OpenSSH form), the user logged in by a private key ([privateKey], when
/// one is given), else by password ([askPassword], asked again when one is
/// refused, three times at most) or the server's questions
/// ([askQuestions], keyboard-interactive); a pty of [term] in the
/// screen's size and a shell on it. What the server says (stdout and
/// stderr) goes to [onData]; [write] sends what is typed; [resize] the
/// window's new size. [onClose] once, with why (nil when it was asked to).
///
/// The callbacks are made on the connection's own thread: hop to the
/// main one to touch views. Host keys: Ed25519 and ECDSA (SwiftNIO SSH
/// has no RSA).
/// main one to touch views. Host keys and the user's: Ed25519, ECDSA and
/// RSA.
public final class SSHShell: @unchecked Sendable {
public let host: String
public let port: Int
@@ -29,17 +29,25 @@ public final class SSHShell: @unchecked Sendable {
/// the user's password, asked ("" when it's the first time, else why
/// the last was refused): call back with nil to give up
public var askPassword: (String, @escaping (String?) -> Void) -> Void = { _, done in done(nil) }
/// the server's questions (keyboard-interactive): its instruction and
/// each question with whether its answer may be shown; call back with
/// the answers, or nil to give up. Unset: passwords are asked by
/// [askPassword] instead
public var askQuestions: ((String, [(String, Bool)], @escaping ([String]?) -> Void) -> Void)?
/// a private key's text (OpenSSH's or PEM) to log in with first, and
/// its passphrase
public var privateKey: (key: String, passphrase: String?)?
private var cols: Int
private var rows: Int
/// (SwiftNIO's shared threads: a shell's owner may let go of it on one)
private let group = MultiThreadedEventLoopGroup.singleton
private var channel: Channel?
private var shell: Channel?
private let lock = NSLock()
private var closed = false
private var closing = false
private var exitStatus: Int?
private let s: OpaquePointer?
private var shell: Int32 = 0
private var started = false
private var asked = false
private var exitStatus = 0
private var triedKey = false
private var asks = 0
/// a shell to log in to: nothing is done until [connect]
public init(host: String, port: Int = 22, user: String, term: String = "xterm-256color", cols: Int = 80, rows: Int = 24) {
@@ -49,265 +57,151 @@ public final class SSHShell: @unchecked Sendable {
self.term = term
self.cols = cols
self.rows = rows
s = dmc_ssh_new(host, Int32(port), user)
}
/// the connection freed
deinit {
// (its thread holds the shell until the connection's over)
if let s { dmc_ssh_free(s) }
}
/// connect, log in and start the shell, on the connection's thread
public func connect() {
let auth = PasswordAuth(user: user) { [weak self] why, done in
guard let self else { return done(nil) }
self.askPassword(why, done)
}
let keys = HostKeyCheck { [weak self] key, done in
guard let self else { return done(false) }
self.verifyHostKey(key, done)
}
let bootstrap = ClientBootstrap(group: group)
.connectTimeout(.seconds(20))
.channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
.channelInitializer { ch in
ch.eventLoop.makeCompletedFuture {
let ssh = NIOSSHHandler(
role: .client(.init(userAuthDelegate: auth, serverAuthDelegate: keys)),
allocator: ch.allocator, inboundChildChannelInitializer: nil)
try ch.pipeline.syncOperations.addHandlers([ssh, ErrorCatcher { [weak self] e in self?.failed(e) }])
guard let s else { return onClose("could not start SSH") }
guard !started else { return }
started = true
let t = Thread { self.run(s) }
t.name = "ssh-\(host)"
t.start()
}
/// the connection's life: each event acted on until it's over
private func run(_ s: OpaquePointer) {
var ev = dmc_ssh_event()
while dmc_ssh_poll(s, 1000, &ev) >= 0 {
if ev.type == 0 { continue }
let data: Data? = ev.data.map { Data(bytes: $0, count: Int(ev.len)) }
let text = data.map { String(decoding: $0, as: UTF8.self) }
let type = Int(ev.type)
ev.type = 0
switch type {
case DMC_SSH_EV_HOSTKEY:
verifyHostKey(text ?? "") { ok in dmc_ssh_trust(s, ok ? 1 : 0, 0) }
case DMC_SSH_EV_AUTH:
login(s, methods: Int(ev.value), why: text ?? "")
case DMC_SSH_EV_PROMPTS:
questions(s, count: Int(ev.value))
case DMC_SSH_EV_READY:
let (c, r) = lock.withLock { (cols, rows) }
let ch = dmc_ssh_shell(s, term, Int32(c), Int32(r), 0)
lock.withLock { shell = ch }
case DMC_SSH_EV_OPEN:
if ev.value == 0 { dmc_ssh_disconnect(s) }
case DMC_SSH_EV_DATA:
if ev.channel == lock.withLock({ shell }), let data { onData(data) }
case DMC_SSH_EV_EXIT:
if ev.channel == lock.withLock({ shell }) { exitStatus = Int(ev.value) }
case DMC_SSH_EV_CLOSE:
// (the shell's over: so is the connection)
if ev.channel == lock.withLock({ shell }) {
lock.withLock { shell = 0 }
dmc_ssh_disconnect(s)
}
}
bootstrap.connect(host: host, port: port).flatMap { [weak self] (ch: Channel) -> EventLoopFuture<Channel> in
guard let self else { return ch.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel) }
self.lock.withLock { self.channel = ch }
ch.closeFuture.whenComplete { [weak self] _ in self?.finish(nil) }
return ch.pipeline.handler(type: NIOSSHHandler.self).flatMap { ssh in
let p = ch.eventLoop.makePromise(of: Channel.self)
ssh.createChannel(p) { child, type in
guard type == .session else {
return child.eventLoop.makeFailedFuture(SSHShellError.unexpectedChannel)
}
return child.setOption(ChannelOptions.allowRemoteHalfClosure, value: true).flatMap {
child.pipeline.addHandler(ShellHandler(owner: self))
}
case DMC_SSH_EV_INCOMING:
dmc_ssh_close(s, ev.channel)
case DMC_SSH_EV_CLOSED:
let byUser = lock.withLock { asked }
if text != nil {
onClose(text)
} else if byUser {
onClose(nil)
} else if exitStatus != 0 {
onClose("the shell exited with status \(exitStatus)")
} else {
onClose("Connection closed")
}
return p.futureResult
return
default:
break
}
}.flatMap { [weak self] (child: Channel) -> EventLoopFuture<Void> in
guard let self else { return child.eventLoop.makeSucceededVoidFuture() }
self.lock.withLock { self.shell = child }
let (c, r) = self.lock.withLock { (self.cols, self.rows) }
let pty = SSHChannelRequestEvent.PseudoTerminalRequest(
wantReply: true, term: self.term, terminalCharacterWidth: c, terminalRowHeight: r,
terminalPixelWidth: 0, terminalPixelHeight: 0, terminalModes: SSHTerminalModes([:]))
return child.triggerUserOutboundEvent(pty).flatMap {
child.triggerUserOutboundEvent(SSHChannelRequestEvent.ShellRequest(wantReply: true))
}
}
/// the next login: the key first, then the server's questions or a
/// password (three times at most)
private func login(_ s: OpaquePointer, methods: Int, why: String) {
if let k = privateKey, !triedKey, methods & DMC_SSH_AUTH_PUBLICKEY != 0 {
triedKey = true
if dmc_ssh_auth_key(s, k.key, k.passphrase) == 0 { return }
}
asks += 1
let interactive = methods & DMC_SSH_AUTH_INTERACTIVE != 0
let password = methods & DMC_SSH_AUTH_PASSWORD != 0
if asks > 3 {
dmc_ssh_auth_cancel(s)
} else if interactive && (askQuestions != nil || !password) {
dmc_ssh_auth_interactive(s)
} else if password {
askPassword(asks == 1 ? "" : (why.isEmpty ? "The password was not accepted" : why)) { pw in
if let pw { dmc_ssh_auth_password(s, pw) } else { dmc_ssh_auth_cancel(s) }
}
}.whenFailure { [weak self] e in self?.failed(e) }
} else {
dmc_ssh_auth_cancel(s)
}
}
/// a round of the server's questions put to the user
private func questions(_ s: OpaquePointer, count: Int) {
if count == 0 { return dmc_ssh_answered(s) }
var qs: [(String, Bool)] = []
for i in 0..<count {
var echo: Int32 = 0
qs.append((String(cString: dmc_ssh_prompt(s, Int32(i), &echo)), echo != 0))
}
let instruction = String(cString: dmc_ssh_instruction(s))
let answer: ([String]?) -> Void = { a in
guard let a else { return dmc_ssh_auth_cancel(s) }
for (i, x) in a.enumerated() { dmc_ssh_answer(s, Int32(i), x) }
dmc_ssh_answered(s)
}
if let askQuestions {
askQuestions(instruction, qs, answer)
} else {
askPassword(asks <= 1 ? "" : "The password was not accepted") { pw in answer(pw.map { [$0] }) }
}
}
/// what's typed, to the shell
public func write(_ data: Data) {
guard let s = lock.withLock({ shell }), !data.isEmpty else { return }
var b = s.allocator.buffer(capacity: data.count)
b.writeBytes(data)
s.writeAndFlush(SSHChannelData(type: .channel, data: .byteBuffer(b)), promise: nil)
guard let s, !data.isEmpty else { return }
let ch = lock.withLock { shell }
guard ch > 0 else { return }
data.withUnsafeBytes { b in
_ = dmc_ssh_write(s, ch, b.baseAddress!.assumingMemoryBound(to: CChar.self), Int32(b.count))
}
}
/// the screen's new size, to the server
public func resize(cols: Int, rows: Int) {
let s: Channel? = lock.withLock {
guard let s else { return }
let ch: Int32? = lock.withLock {
guard cols != self.cols || rows != self.rows else { return nil }
self.cols = cols
self.rows = rows
return shell
}
s?.triggerUserOutboundEvent(SSHChannelRequestEvent.WindowChangeRequest(
terminalCharacterWidth: cols, terminalRowHeight: rows, terminalPixelWidth: 0, terminalPixelHeight: 0), promise: nil)
if let ch, ch > 0 { dmc_ssh_resize(s, ch, Int32(cols), Int32(rows)) }
}
/// the connection closed by the user
public func close() {
let ch: Channel? = lock.withLock {
closing = true
return channel
}
if let ch {
ch.close(promise: nil)
guard let s else { return }
lock.withLock { asked = true }
if started {
dmc_ssh_disconnect(s)
} else {
finish(nil)
}
}
/// the server's data, to [onData]
fileprivate func received(_ data: Data) { onData(data) }
/// the shell's exit status, kept for [onClose]
fileprivate func exited(_ status: Int) { lock.withLock { exitStatus = status } }
/// the shell's channel closed: the connection is closed too
fileprivate func shellClosed() {
// (the shell's over: so is the connection)
lock.withLock { channel }?.close(promise: nil)
}
/// an error: [onClose] told why, the connection closed
fileprivate func failed(_ e: Error) {
finish(Self.describe(e))
lock.withLock { channel }?.close(promise: nil)
}
/// [onClose] called, once, with why
private func finish(_ why: String?) {
let (first, asked, status): (Bool, Bool, Int?) = lock.withLock {
defer { closed = true }
return (!closed, closing, exitStatus)
}
guard first else { return }
if asked {
onClose(nil)
} else if let why {
onClose(why)
} else if let status, status != 0 {
onClose("the shell exited with status \(status)")
} else {
onClose("Connection closed")
}
}
/// an error in words for the user
static func describe(_ e: Error) -> String {
switch e {
case SSHShellError.hostKeyRefused: return "the host's key was not accepted"
case SSHShellError.noPassword: return "not logged in"
case SSHShellError.unexpectedChannel: return "the server opened an unexpected channel"
default: break
}
if let n = e as? NIOSSHError {
switch n.type {
case .invalidHostKeyForKeyExchange, .keyExchangeNegotiationFailure:
return "no host key or key exchange in common (this app has Ed25519 and ECDSA, not RSA)"
default:
break
}
}
if e is NIOConnectionError || e is IOError { return "could not connect: \(e)" }
return "\(e)"
}
}
public enum SSHShellError: Error {
case hostKeyRefused, noPassword, unexpectedChannel
}
/// the password, asked; again (with why) when the server refuses it, three times at most
private final class PasswordAuth: NIOSSHClientUserAuthenticationDelegate {
let user: String
let ask: (String, @escaping (String?) -> Void) -> Void
var tries = 0
/// asks [ask] for the password for [user]
init(user: String, ask: @escaping (String, @escaping (String?) -> Void) -> Void) {
self.user = user
self.ask = ask
}
/// the next password offered, or a failure once there are none
func nextAuthenticationType(
availableMethods: NIOSSHAvailableUserAuthenticationMethods,
nextChallengePromise: EventLoopPromise<NIOSSHUserAuthenticationOffer?>
) {
guard availableMethods.contains(.password) else {
nextChallengePromise.fail(SSHShellError.noPassword)
return
}
guard tries < 3 else {
nextChallengePromise.fail(SSHShellError.noPassword)
return
}
tries += 1
let user = self.user
ask(tries == 1 ? "" : "The password was not accepted") { pw in
guard let pw else {
nextChallengePromise.fail(SSHShellError.noPassword)
return
}
nextChallengePromise.succeed(NIOSSHUserAuthenticationOffer(
username: user, serviceName: "", offer: .password(.init(password: pw))))
}
}
}
/// the host's key, as OpenSSH writes it, to the caller to accept or not
private final class HostKeyCheck: NIOSSHClientServerAuthenticationDelegate {
let verify: (String, @escaping (Bool) -> Void) -> Void
/// asks [verify] about each host key
init(verify: @escaping (String, @escaping (Bool) -> Void) -> Void) {
self.verify = verify
}
/// the host's key, to the caller to accept or refuse
func validateHostKey(hostKey: NIOSSHPublicKey, validationCompletePromise: EventLoopPromise<Void>) {
verify(String(openSSHPublicKey: hostKey)) { ok in
if ok {
validationCompletePromise.succeed(())
} else {
validationCompletePromise.fail(SSHShellError.hostKeyRefused)
}
}
}
}
/// the shell's channel: its data (stdout and stderr) to the owner, its exit status kept
private final class ShellHandler: ChannelInboundHandler {
typealias InboundIn = SSHChannelData
private weak var owner: SSHShell?
/// for [owner]'s shell
init(owner: SSHShell) {
self.owner = owner
}
/// the server's data, to the owner
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let d = unwrapInboundIn(data)
guard case .byteBuffer(var b) = d.data, let bytes = b.readBytes(length: b.readableBytes) else { return }
owner?.received(Data(bytes))
}
/// the exit status kept; the shell closed when the server's output ends
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
if let s = event as? SSHChannelRequestEvent.ExitStatus {
owner?.exited(s.exitStatus)
} else if event is ChannelEvent, case .inputClosed = event as! ChannelEvent {
context.close(promise: nil)
}
context.fireUserInboundEventTriggered(event)
}
/// the shell's channel gone: the owner told
func channelInactive(context: ChannelHandlerContext) {
owner?.shellClosed()
context.fireChannelInactive()
}
/// the error to the owner, the channel closed
func errorCaught(context: ChannelHandlerContext, error: Error) {
owner?.failed(error)
context.close(promise: nil)
}
}
/// the connection's errors (a refused host key, a failed login) to the owner
private final class ErrorCatcher: ChannelInboundHandler {
typealias InboundIn = Any
let caught: (Error) -> Void
/// [caught] told of each error
init(caught: @escaping (Error) -> Void) {
self.caught = caught
}
/// the error to the owner, the connection closed
func errorCaught(context: ChannelHandlerContext, error: Error) {
caught(error)
context.close(promise: nil)
}
}
+79 -1
View File
@@ -6,7 +6,8 @@
# D-Modem, libre and Mbed TLS, built for iOS (devices), the iOS
# simulator and macOS, each as one static library, together as
# build-apple/DModemEngine.xcframework (its header dmodem_engine.h, its
# module DModemEngine: Swift imports it).
# module DModemEngine: Swift imports it). And the SSH client
# (native-ssh) the same way, as build-apple/DModemSSHNative.xcframework.
#
# ios/build-native.sh (macOS with Xcode, CMake and Ninja)
#
@@ -73,3 +74,80 @@ xcodebuild -create-xcframework \
-library "$OUT/macos/libDModemEngine.a" -headers "$inc" \
-output "$OUT/DModemEngine.xcframework"
echo "built $OUT/DModemEngine.xcframework"
# The SSH client (native-ssh: libdmodemssh on libssh and Mbed TLS) as
# build-apple/DModemSSHNative.xcframework (module CDModemSSH), for
# ios/DModemSSH. Its Mbed TLS is not the engine's (libre's, another
# release, without threads), so each arch's libraries are linked into one
# object whose only global symbols are dmc_ssh_*: the two never meet.
# ssh_arch <name> <system> <sdk> <arch> <min>: $OUT/<name>/ssh-<arch>.o
ssh_arch() {
name=$1 system=$2 sdk=$3 arch=$4 min=$5
dir=$OUT/$name/ssh-$arch
echo "== SSH $name ($sdk, $arch)"
set -- -S "$ROOT/native-ssh" -B "$dir" -G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_OSX_SYSROOT="$sdk" \
-DCMAKE_OSX_ARCHITECTURES="$arch" \
-DCMAKE_OSX_DEPLOYMENT_TARGET="$min"
[ "$system" = iOS ] && set -- "$@" -DCMAKE_SYSTEM_NAME=iOS
cmake "$@"
cmake --build "$dir" --target dmodemssh
objs=$dir/objs
rm -rf "$objs"
mkdir -p "$objs"
# (each archive's objects apart: their names repeat between them)
i=0
for a in "$dir/libdmodemssh.a" "$dir/dmodem-libssh/lib/libssh.a" \
"$dir"/dmodem-libssh/lib/libmbed*.a "$dir/dmodem-libssh/lib/libeverest.a" \
"$dir/dmodem-libssh/lib/libp256m.a"; do
i=$((i + 1))
mkdir -p "$objs/$i"
(cd "$objs/$i" && ar x "$a")
done
printf '_dmc_ssh_*\n' > "$dir/exports"
xcrun ld -r -arch "$arch" -exported_symbols_list "$dir/exports" \
"$objs"/*/*.o -o "$OUT/$name/ssh-$arch.o"
}
# ssh_slice <name> <system> <sdk> <min> <arch>...: $OUT/<name>/libDModemSSHNative.a
ssh_slice() {
name=$1 system=$2 sdk=$3 min=$4
shift 4
libs=
for arch in "$@"; do
ssh_arch "$name" "$system" "$sdk" "$arch" "$min"
rm -f "$OUT/$name/ssh-$arch.a"
libtool -static -o "$OUT/$name/ssh-$arch.a" "$OUT/$name/ssh-$arch.o"
libs="$libs $OUT/$name/ssh-$arch.a"
done
# (one archive per arch, then one universal one of them)
rm -f "$OUT/$name/libDModemSSHNative.a"
lipo -create $libs -output "$OUT/$name/libDModemSSHNative.a"
}
ssh_slice ios iOS iphoneos "$IOS_MIN" arm64
ssh_slice ios-simulator iOS iphonesimulator "$IOS_MIN" arm64 x86_64
ssh_slice macos Darwin macosx "$MACOS_MIN" arm64 x86_64
# (in a directory of its own: an app's XCFrameworks' headers all land in
# one include/, and the engine's module.modulemap is there already)
sinc=$OUT/include-ssh
rm -rf "$sinc"
mkdir -p "$sinc/CDModemSSH"
cp "$ROOT/native-ssh/include/dmodemssh.h" "$sinc/CDModemSSH/"
cat > "$sinc/CDModemSSH/module.modulemap" <<MAP
module CDModemSSH {
header "dmodemssh.h"
export *
}
MAP
rm -rf "$OUT/DModemSSHNative.xcframework"
xcodebuild -create-xcframework \
-library "$OUT/ios/libDModemSSHNative.a" -headers "$sinc" \
-library "$OUT/ios-simulator/libDModemSSHNative.a" -headers "$sinc" \
-library "$OUT/macos/libDModemSSHNative.a" -headers "$sinc" \
-output "$OUT/DModemSSHNative.xcframework"
echo "built $OUT/DModemSSHNative.xcframework"
+53
View File
@@ -0,0 +1,53 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 Neo-Desktop
#
# libdmodemssh: the apps' SSH client (dmodemssh.h) on libssh 0.11 and
# mbedTLS, both built here from their release tarballs (checked by hash).
# The same engine as D-Modem/gui's ssh/: Android loads it through JNI
# (app/src/main/cpp), iOS as ios/build-native.sh's DModemSSHNative
# XCFramework, and here on the build host for its tests:
#
# cmake -S native-ssh -B build-ssh && cmake --build build-ssh
# DMODEM_SSH_TEST=host:port:user:password build-ssh/dmodemssh_test
cmake_minimum_required(VERSION 3.22)
project(dmodemssh LANGUAGES C)
include(${CMAKE_CURRENT_LIST_DIR}/cmake/BundledLibssh.cmake)
add_library(dmodemssh STATIC src/dmodemssh.c)
target_include_directories(dmodemssh PUBLIC include)
target_link_libraries(dmodemssh PUBLIC dmodem_libssh)
set_target_properties(dmodemssh PROPERTIES POSITION_INDEPENDENT_CODE ON)
if(NOT WIN32)
find_package(Threads REQUIRED)
target_link_libraries(dmodemssh PUBLIC Threads::Threads)
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)
target_link_libraries(dmodemssh_test PRIVATE dmodemssh)
add_test(NAME dmodemssh COMMAND dmodemssh_test)
endif()
+98
View File
@@ -0,0 +1,98 @@
# libssh on mbedTLS, both static, built from their release tarballs
# (checked by hash), as the target dmodem_libssh.
include(FetchContent)
include(ExternalProject)
set(DMODEM_MBEDTLS_URL https://github.com/Mbed-TLS/mbedtls/releases/download/mbedtls-3.6.4/mbedtls-3.6.4.tar.bz2)
set(DMODEM_MBEDTLS_SHA256 ec35b18a6c593cf98c3e30db8b98ff93e8940a8c4e690e66b41dfc011d678110)
set(DMODEM_LIBSSH_URL https://www.libssh.org/files/0.11/libssh-0.11.3.tar.xz)
set(DMODEM_LIBSSH_SHA256 7d8a1361bb094ec3f511964e78a5a4dba689b5986e112afabe4f4d0d6c6125c3)
set(_prefix ${CMAKE_BINARY_DIR}/dmodem-libssh)
set(_args
-DCMAKE_BUILD_TYPE=Release
-DCMAKE_INSTALL_PREFIX=${_prefix}
-DCMAKE_INSTALL_LIBDIR=lib
-DCMAKE_POSITION_INDEPENDENT_CODE=ON
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
-DCMAKE_MSVC_RUNTIME_LIBRARY=${CMAKE_MSVC_RUNTIME_LIBRARY}
-DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES}
-DCMAKE_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET}
-DCMAKE_OSX_SYSROOT=${CMAKE_OSX_SYSROOT})
if(CMAKE_TOOLCHAIN_FILE)
list(APPEND _args -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE})
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "iOS")
list(APPEND _args -DCMAKE_SYSTEM_NAME=iOS)
endif()
if(ANDROID)
list(APPEND _args -DANDROID_ABI=${ANDROID_ABI} -DANDROID_PLATFORM=${ANDROID_PLATFORM})
endif()
if(CMAKE_MAKE_PROGRAM)
list(APPEND _args -DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM})
endif()
string(REPLACE ";" "|" _archs "${CMAKE_OSX_ARCHITECTURES}")
list(TRANSFORM _args REPLACE "^-DCMAKE_OSX_ARCHITECTURES=.*" "-DCMAKE_OSX_ARCHITECTURES=${_archs}")
if(WIN32)
set(_mbed_libs mbedcrypto.lib mbedx509.lib mbedtls.lib everest.lib p256m.lib)
set(_ssh_lib ssh.lib)
if(MINGW)
set(_mbed_libs libmbedcrypto.a libmbedx509.a libmbedtls.a libeverest.a libp256m.a)
set(_ssh_lib libssh.a)
endif()
else()
set(_mbed_libs libmbedcrypto.a libmbedx509.a libmbedtls.a libeverest.a libp256m.a)
set(_ssh_lib libssh.a)
endif()
list(TRANSFORM _mbed_libs PREPEND ${_prefix}/lib/ OUTPUT_VARIABLE _mbed_paths)
ExternalProject_Add(dmodem_mbedtls
URL ${DMODEM_MBEDTLS_URL}
URL_HASH SHA256=${DMODEM_MBEDTLS_SHA256}
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
PATCH_COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_LIST_DIR}/PatchMbedtls.cmake
LIST_SEPARATOR |
CMAKE_ARGS ${_args} -DENABLE_TESTING=OFF -DENABLE_PROGRAMS=OFF
-DUSE_SHARED_MBEDTLS_LIBRARY=OFF -DMBEDTLS_FATAL_WARNINGS=OFF
BUILD_BYPRODUCTS ${_mbed_paths})
# (Bionic has no S_IWRITE, the old name libssh uses)
set(_ssh_args)
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=ON
-DWITH_EXAMPLES=OFF -DUNIT_TESTING=OFF -DCLIENT_TESTING=OFF
-DWITH_NACL=OFF -DWITH_SYMBOL_VERSIONING=OFF
BUILD_BYPRODUCTS ${_prefix}/lib/${_ssh_lib})
file(MAKE_DIRECTORY ${_prefix}/include)
add_library(dmodem_libssh INTERFACE)
add_dependencies(dmodem_libssh dmodem_libssh_build)
target_include_directories(dmodem_libssh INTERFACE ${_prefix}/include)
target_compile_definitions(dmodem_libssh INTERFACE LIBSSH_STATIC=1)
target_link_libraries(dmodem_libssh INTERFACE ${_prefix}/lib/${_ssh_lib} ${_mbed_paths})
if(WIN32)
target_link_libraries(dmodem_libssh INTERFACE ws2_32 iphlpapi bcrypt shell32 advapi32)
# (MinGW's libssh locks with winpthreads)
if(MINGW)
target_link_libraries(dmodem_libssh INTERFACE pthread)
endif()
elseif(UNIX)
find_package(Threads REQUIRED)
target_link_libraries(dmodem_libssh INTERFACE Threads::Threads)
endif()
+49
View File
@@ -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;
}")
+24
View File
@@ -0,0 +1,24 @@
# mbedTLS's config with threading on, as libssh wants it: its own
# pthread mutexes, or (Windows) libssh's given through threading_alt.h.
# Run in mbedTLS's source tree by BundledLibssh.cmake.
set(_config include/mbedtls/mbedtls_config.h)
file(READ ${_config} _text)
if(NOT _text MATCHES "D-Modem: threading")
file(APPEND ${_config} "
/* D-Modem: threading, for libssh */
#define MBEDTLS_THREADING_C
#if defined(_WIN32)
#define MBEDTLS_THREADING_ALT
#else
#define MBEDTLS_THREADING_PTHREAD
#endif
")
endif()
file(WRITE include/mbedtls/threading_alt.h "/* D-Modem: libssh's mutexes (a pointer each) */
#ifndef DMODEM_THREADING_ALT_H
#define DMODEM_THREADING_ALT_H
typedef struct mbedtls_threading_mutex_t {
void *mutex;
} mbedtls_threading_mutex_t;
#endif
")
+182
View File
@@ -0,0 +1,182 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* dmodemssh.h - D-Modem's SSH client, on libssh: the one engine every
* app has (the desktops', iOS's, and Android's through JNI), so that
* each has the same SSH.
*
* A connection (dmc_ssh) is driven by one thread that calls
* dmc_ssh_poll() in a loop and acts on the events it hands back: the
* server's key to trust or not, a login method to choose, a
* keyboard-interactive round to answer, a channel's data. Every other
* call may come from any thread (a lock is taken): what is typed, a
* window's new size, the answers.
*
* What it has: host keys checked by the caller (and in OpenSSH's
* known_hosts when asked); logins by password, keyboard-interactive, a
* private key (OpenSSH's, PEM), the system's agent, or OpenSSH's own
* keys and agent at once (ssh's default); ~/.ssh/config when asked; Ed25519,
* ECDSA and RSA keys; a shell on a pty, a command, direct TCP channels
* (ssh -L and -D), remote listens (ssh -R) and the server's
* agent channels (ssh -A) handed to the caller as channels.
*
* This file and dmodemssh.c are the same in D-Modem/gui (ssh/) and
* D-Modem/app (native-ssh/): change both.
*/
#ifndef DMODEMSSH_H
#define DMODEMSSH_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct dmc_ssh dmc_ssh;
/* what dmc_ssh_poll() hands back */
enum {
DMC_SSH_EV_HOSTKEY = 1, /* the server's key: data is its OpenSSH line
("ssh-ed25519 AAAA..."), value a
DMC_SSH_HOST_*; answer dmc_ssh_trust() */
DMC_SSH_EV_AUTH, /* a login method wanted: value is the
DMC_SSH_AUTH_* the server takes, data why
the last failed ("" the first time);
answer one dmc_ssh_auth_*() */
DMC_SSH_EV_PROMPTS, /* the server's questions (keyboard-
interactive): value how many, data the
round's name; read them with
dmc_ssh_prompt(), answer each with
dmc_ssh_answer(), then dmc_ssh_answered() */
DMC_SSH_EV_READY, /* logged in: data the server's banner, if any */
DMC_SSH_EV_OPEN, /* a channel opened (value 1) or refused
(value 0, data why) */
DMC_SSH_EV_DATA, /* a channel's data (value 1: its stderr) */
DMC_SSH_EV_EOF, /* a channel's end of data */
DMC_SSH_EV_EXIT, /* a command's exit status (value), or the
signal that ended it (data) */
DMC_SSH_EV_CLOSE, /* a channel closed: its number is free */
DMC_SSH_EV_INCOMING, /* a channel the server opened, open now:
value DMC_SSH_IN_AGENT, or the remote
listen's port (data: who connected) */
DMC_SSH_EV_LISTEN, /* a remote listen (channel: its request's
number) answered: value the port bound,
-1 refused */
DMC_SSH_EV_CLOSED /* the connection over: data why (NULL when
dmc_ssh_disconnect() asked) */
};
typedef struct dmc_ssh_event {
int type;
int channel; /* the channel it's about (1 and up), or 0 */
int value;
const char *data; /* until the next dmc_ssh_poll() */
int len;
} dmc_ssh_event;
/* the server's key against OpenSSH's known_hosts (when the
"knownhosts" option was given) */
enum {
DMC_SSH_HOST_UNCHECKED = 0, DMC_SSH_HOST_KNOWN, DMC_SSH_HOST_NEW,
DMC_SSH_HOST_CHANGED, DMC_SSH_HOST_OTHER_TYPE
};
/* the login methods the server takes */
enum {
DMC_SSH_AUTH_PASSWORD = 1, DMC_SSH_AUTH_PUBLICKEY = 2,
DMC_SSH_AUTH_INTERACTIVE = 4
};
/* a server-opened channel that is the agent's (ssh -A) */
enum { DMC_SSH_IN_AGENT = -1 };
/* 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);
/* the connection dropped (if it's up) and freed */
void dmc_ssh_free(dmc_ssh *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);
/* 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);
/* the connection closed by the user: a DMC_SSH_EV_CLOSED with NULL comes */
void dmc_ssh_disconnect(dmc_ssh *s);
/* the server's key: trusted (ok) or not; remember: added to known_hosts */
void dmc_ssh_trust(dmc_ssh *s, int ok, int remember);
/* a login tried (an answer to DMC_SSH_EV_AUTH) */
void dmc_ssh_auth_password(dmc_ssh *s, const char *password);
/* 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);
/* by the system's agent (SSH_AUTH_SOCK) */
void dmc_ssh_auth_agent(dmc_ssh *s);
/* as OpenSSH's ssh does: the agent, then ~/.ssh's keys with no passphrase */
void dmc_ssh_auth_auto(dmc_ssh *s);
/* by the server's questions (keyboard-interactive) */
void dmc_ssh_auth_interactive(dmc_ssh *s);
/* no more tries: the connection closes, "not logged in" */
void dmc_ssh_auth_cancel(dmc_ssh *s);
/* a DMC_SSH_EV_PROMPTS round: its instruction, and question i (*echo:
whether the answer may be shown) */
const char *dmc_ssh_instruction(dmc_ssh *s);
const char *dmc_ssh_prompt(dmc_ssh *s, int i, int *echo);
void dmc_ssh_answer(dmc_ssh *s, int i, const char *answer);
void dmc_ssh_answered(dmc_ssh *s);
/* channels, once ready: each a number (1 and up), or -1; a
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; 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,
const char *from_host, int from_port);
/* 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);
/* 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): 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);
/* the channel closed (a DMC_SSH_EV_CLOSE comes) */
void dmc_ssh_close(dmc_ssh *s, int channel);
/* a shell's pty resized */
void dmc_ssh_resize(dmc_ssh *s, int channel, int cols, int rows);
/* keys */
/* 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);
/* 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);
/* 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);
/* 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);
void dmc_ssh_free_string(char *str);
#ifdef __cplusplus
}
#endif
#endif
+289
View File
@@ -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 <jni.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#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;
}
File diff suppressed because it is too large. Load diff
+359
View File
@@ -0,0 +1,359 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* dmodemssh_test.c - libdmodemssh's tests: keys (always), and a login to
* a real sshd when DMODEM_SSH_TEST names one as host:port:user:password
* (a shell, a command, a direct channel and a remote listen on it).
* DMODEM_SSH_TEST_KEY, a private key's file that the user's
* authorized_keys has, adds a login by key.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#define closesocket close
#endif
#include "dmodemssh.h"
static int failures;
#define CHECK(c) do { if (!(c)) { \
fprintf(stderr, "%s:%d: failed: %s\n", __FILE__, __LINE__, #c); \
failures++; } } while (0)
/* a key made, read back, its fingerprint, and with a passphrase */
static void test_keys(void)
{
static const char *types[] = { "ed25519", "ecdsa", "rsa" };
static const int bits[] = { 0, 384, 2048 };
int i;
for (i = 0; i < 3; i++) {
char *priv = NULL, *pub = NULL, *pub2 = NULL, *enc = NULL;
char fp[128];
CHECK(dmc_ssh_keygen(types[i], bits[i], NULL, &priv, &pub) == 0);
if (!priv || !pub)
continue;
CHECK(strstr(priv, "BEGIN OPENSSH PRIVATE KEY") != NULL);
CHECK(dmc_ssh_key_public(priv, NULL, &pub2) == 0);
CHECK(pub2 && !strcmp(pub, pub2));
CHECK(dmc_ssh_fingerprint(pub, fp, sizeof fp) == 0);
CHECK(!strncmp(fp, "SHA256:", 7) && strlen(fp) == 50);
CHECK(dmc_ssh_key_export(priv, NULL, "sesame", &enc) == 0);
dmc_ssh_free_string(pub2);
pub2 = NULL;
CHECK(enc && dmc_ssh_key_public(enc, "wrong", &pub2) < 0);
CHECK(enc && dmc_ssh_key_public(enc, "sesame", &pub2) == 0);
CHECK(pub2 && !strcmp(pub, pub2));
dmc_ssh_free_string(priv);
dmc_ssh_free_string(pub);
dmc_ssh_free_string(pub2);
dmc_ssh_free_string(enc);
}
{
char fp[128];
CHECK(dmc_ssh_fingerprint("ssh-ed25519 notbase64!", fp, sizeof fp) < 0);
}
}
static const char *host, *user, *password;
static int port;
/* the next event (10 s at most): its type, or 0 */
static int next(dmc_ssh *s, dmc_ssh_event *ev)
{
int r = dmc_ssh_poll(s, 10000, ev);
if (r <= 0) {
fprintf(stderr, "no event (%d)\n", r);
return 0;
}
return ev->type;
}
/* a connection logged in by password (a wrong one first): or NULL */
static dmc_ssh *logged_in(void)
{
dmc_ssh *s = dmc_ssh_new(host, port, user);
dmc_ssh_event ev;
CHECK(next(s, &ev) == DMC_SSH_EV_HOSTKEY);
CHECK(!strncmp(ev.data, "ssh-", 4) || !strncmp(ev.data, "ecdsa-", 6));
CHECK(ev.value == DMC_SSH_HOST_UNCHECKED);
dmc_ssh_trust(s, 1, 0);
CHECK(next(s, &ev) == DMC_SSH_EV_AUTH);
CHECK(ev.value & DMC_SSH_AUTH_PASSWORD);
CHECK(!strcmp(ev.data, ""));
dmc_ssh_auth_password(s, "not it");
CHECK(next(s, &ev) == DMC_SSH_EV_AUTH);
CHECK(!strcmp(ev.data, "The password was not accepted"));
dmc_ssh_auth_password(s, password);
if (next(s, &ev) != DMC_SSH_EV_READY) {
CHECK(!"logged in");
dmc_ssh_free(s);
return NULL;
}
return s;
}
/* a channel's output read until it closes: into out; its exit status */
static int drain(dmc_ssh *s, int ch, char *out, int max)
{
dmc_ssh_event ev;
int len = 0, status = -1000;
for (;;) {
int t = next(s, &ev);
if (!t || t == DMC_SSH_EV_CLOSED)
break;
if (ev.channel != ch)
continue;
if (t == DMC_SSH_EV_DATA && len + ev.len < max) {
memcpy(out + len, ev.data, (size_t)ev.len);
len += ev.len;
} else if (t == DMC_SSH_EV_EXIT) {
status = ev.value;
} else if (t == DMC_SSH_EV_CLOSE) {
break;
}
}
out[len] = 0;
return status;
}
/* a shell on a pty: its size, a command typed, its exit */
static void test_shell(dmc_ssh *s)
{
dmc_ssh_event ev;
char out[8192];
int ch = dmc_ssh_shell(s, "vt100", 100, 30, 0);
static const char typed[] = "stty size; echo $TERM; exit 3\n";
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(drain(s, ch, out, sizeof out) == 3);
CHECK(strstr(out, "30 100") != NULL);
CHECK(strstr(out, "vt100") != NULL);
CHECK(dmc_ssh_write(s, ch, "x", 1) < 0);
}
/* a command: its output, stdin, and exit status */
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", 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);
dmc_ssh_eof(s, ch);
CHECK(drain(s, ch, out, sizeof out) == 7);
CHECK(!strcmp(out, "HELLO\n"));
}
/* a direct channel to the sshd itself: its banner */
static void test_direct(dmc_ssh *s)
{
dmc_ssh_event ev;
int ch = dmc_ssh_direct(s, "127.0.0.1", port, "127.0.0.1", 40000);
int t;
CHECK(ch > 0);
CHECK(next(s, &ev) == DMC_SSH_EV_OPEN && ev.value == 1);
do {
t = next(s, &ev);
} while (t && t != DMC_SSH_EV_DATA);
CHECK(t == DMC_SSH_EV_DATA && !strncmp(ev.data, "SSH-2.0-", 8));
dmc_ssh_close(s, ch);
CHECK(next(s, &ev) == DMC_SSH_EV_CLOSE && ev.channel == ch);
}
/* a remote listen on a port the server picks, connected to from here */
static void test_listen(dmc_ssh *s)
{
dmc_ssh_event ev;
int id = dmc_ssh_listen(s, "127.0.0.1", 0), bound, ch, t;
struct sockaddr_in a;
int fd;
char b[16];
CHECK(id > 0);
CHECK(next(s, &ev) == DMC_SSH_EV_LISTEN && ev.channel == id);
bound = ev.value;
CHECK(bound > 0);
if (bound <= 0)
return;
fd = (int)socket(AF_INET, SOCK_STREAM, 0);
memset(&a, 0, sizeof a);
a.sin_family = AF_INET;
a.sin_port = htons((unsigned short)bound);
a.sin_addr.s_addr = htonl(0x7f000001);
CHECK(connect(fd, (struct sockaddr *)&a, sizeof a) == 0);
send(fd, "ping", 4, 0);
CHECK(next(s, &ev) == DMC_SSH_EV_INCOMING && ev.value == bound);
ch = ev.channel;
do {
t = next(s, &ev);
} 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);
{
/* (the reply comes as the session is polled) */
int got = 0, i;
for (i = 0; i < 40 && got < 4; i++) {
dmc_ssh_poll(s, 50, &ev);
#ifdef _WIN32
{
u_long n = 0;
ioctlsocket(fd, FIONREAD, &n);
if (n >= 4)
got = recv(fd, b, 4, 0);
}
#else
got = (int)recv(fd, b, 4, MSG_DONTWAIT);
if (got < 0)
got = 0;
#endif
}
CHECK(got == 4 && !memcmp(b, "pong", 4));
}
closesocket(fd);
dmc_ssh_close(s, ch);
dmc_ssh_unlisten(s, "127.0.0.1", bound);
}
/* a login by a key in a file */
static void test_key_login(const char *file)
{
FILE *f = fopen(file, "rb");
char key[16384];
size_t n;
dmc_ssh *s;
dmc_ssh_event ev;
CHECK(f != NULL);
if (!f)
return;
n = fread(key, 1, sizeof key - 1, f);
key[n] = 0;
fclose(f);
s = dmc_ssh_new(host, port, user);
CHECK(next(s, &ev) == DMC_SSH_EV_HOSTKEY);
dmc_ssh_trust(s, 1, 0);
CHECK(next(s, &ev) == DMC_SSH_EV_AUTH && (ev.value & DMC_SSH_AUTH_PUBLICKEY));
CHECK(dmc_ssh_auth_key(s, key, NULL) == 0);
CHECK(next(s, &ev) == DMC_SSH_EV_READY);
dmc_ssh_free(s);
}
/* the logins and channels against DMODEM_SSH_TEST's sshd */
static void test_live(const char *spec)
{
static char buf[512];
char *p[4];
int i;
dmc_ssh *s;
dmc_ssh_event ev;
const char *key = getenv("DMODEM_SSH_TEST_KEY");
snprintf(buf, sizeof buf, "%s", spec);
p[0] = buf;
for (i = 1; i < 4; i++) {
p[i] = strchr(p[i - 1], ':');
if (!p[i]) {
fprintf(stderr, "DMODEM_SSH_TEST: host:port:user:password\n");
failures++;
return;
}
*p[i]++ = 0;
}
host = p[0];
port = atoi(p[1]);
user = p[2];
password = p[3];
s = logged_in();
if (!s)
return;
test_shell(s);
test_exec(s);
test_direct(s);
test_listen(s);
dmc_ssh_disconnect(s);
while (next(s, &ev) && ev.type != DMC_SSH_EV_CLOSED)
;
CHECK(ev.type == DMC_SSH_EV_CLOSED && ev.data == NULL);
CHECK(dmc_ssh_poll(s, 10, &ev) == -1);
dmc_ssh_free(s);
/* a refused key: the connection ends saying so */
s = dmc_ssh_new(host, port, user);
CHECK(next(s, &ev) == DMC_SSH_EV_HOSTKEY);
dmc_ssh_trust(s, 0, 0);
CHECK(next(s, &ev) == DMC_SSH_EV_CLOSED);
CHECK(ev.data && !strcmp(ev.data, "the host's key was not accepted"));
dmc_ssh_free(s);
/* keyboard-interactive, when the server has it: the password asked */
s = dmc_ssh_new(host, port, user);
CHECK(next(s, &ev) == DMC_SSH_EV_HOSTKEY);
dmc_ssh_trust(s, 1, 0);
CHECK(next(s, &ev) == DMC_SSH_EV_AUTH);
if (ev.value & DMC_SSH_AUTH_INTERACTIVE) {
int echo = 1;
dmc_ssh_auth_interactive(s);
CHECK(next(s, &ev) == DMC_SSH_EV_PROMPTS && ev.value == 1);
CHECK(strstr(dmc_ssh_prompt(s, 0, &echo), "assword") != NULL);
CHECK(echo == 0);
dmc_ssh_answer(s, 0, password);
dmc_ssh_answered(s);
/* (some servers end with a round of no questions) */
while (next(s, &ev) == DMC_SSH_EV_PROMPTS && ev.value == 0)
dmc_ssh_answered(s);
CHECK(ev.type == DMC_SSH_EV_READY);
} else {
printf("no keyboard-interactive: not tested\n");
}
dmc_ssh_free(s);
if (key)
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");
#ifdef _WIN32
WSADATA w;
WSAStartup(MAKEWORD(2, 2), &w);
#endif
test_keys();
if (spec)
test_live(spec);
else
printf("DMODEM_SSH_TEST is not set: no login tested\n");
if (failures) {
fprintf(stderr, "%d failed\n", failures);
return 1;
}
printf("ok\n");
return 0;
}