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