From 55bd6015da60b5d10263d7eaf2e334b1db8ee145 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 13:15:49 +0000 Subject: [PATCH] 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; +}