mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B82eRSV65geuGd6zMt2V6r
This commit is contained in:
13 files changed
+2252
-335
No files matched your search
@@ -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
|
||||
|
||||
@@ -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/
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
{
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "swift-asn1",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-asn1.git",
|
||||
"state" : {
|
||||
"revision" : "917b472dbe53ba699cbb0495f9a95a084bc6364d",
|
||||
"version" : "1.7.4"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-atomics",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-atomics.git",
|
||||
"state" : {
|
||||
"revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34",
|
||||
"version" : "1.3.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-collections",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-collections.git",
|
||||
"state" : {
|
||||
"revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a",
|
||||
"version" : "1.6.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-crypto",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-crypto.git",
|
||||
"state" : {
|
||||
"revision" : "da9d28d69ebe3894b18376c8f2395c2f37b8448f",
|
||||
"version" : "4.5.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-nio",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-nio.git",
|
||||
"state" : {
|
||||
"revision" : "2f58d8ef84438d6517fc78bcea2f8527e3c72936",
|
||||
"version" : "2.105.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-nio-ssh",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-nio-ssh.git",
|
||||
"state" : {
|
||||
"revision" : "d1985926494b624e751b379009dc83f3395fd88a",
|
||||
"version" : "0.15.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-system",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-system.git",
|
||||
"state" : {
|
||||
"revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750",
|
||||
"version" : "1.8.1"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
+22
-11
@@ -3,24 +3,35 @@
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
//
|
||||
// DModemSSH: the iOS app's SSH client, an interactive shell on a pty, on
|
||||
// Apple's SwiftNIO SSH. Apart from the app so that it builds and its tests
|
||||
// run on Linux too (against a local sshd, when DMODEM_SSH_TEST names one).
|
||||
// libdmodemssh (native-ssh: the same engine as the Android and desktop
|
||||
// apps', on libssh). On Apple's systems that is build-apple's XCFramework
|
||||
// (ios/build-native.sh); on Linux the host build's libraries (cmake -S
|
||||
// native-ssh -B build-ssh, or DMODEM_SSH_HOST_BUILD), so that its tests
|
||||
// run there too (against a local sshd, when DMODEM_SSH_TEST names one).
|
||||
import Foundation
|
||||
import PackageDescription
|
||||
|
||||
#if os(Linux)
|
||||
let host = ProcessInfo.processInfo.environment["DMODEM_SSH_HOST_BUILD"] ?? "../../build-ssh"
|
||||
let native: Target = .systemLibrary(name: "CDModemSSH", path: "Sources/CDModemSSHHost")
|
||||
let nativeLinking: [LinkerSetting] = [
|
||||
.unsafeFlags(["-L\(host)", "-L\(host)/dmodem-libssh/lib"]),
|
||||
.linkedLibrary("dmodemssh"), .linkedLibrary("ssh"),
|
||||
.linkedLibrary("mbedtls"), .linkedLibrary("mbedx509"), .linkedLibrary("mbedcrypto"),
|
||||
.linkedLibrary("everest"), .linkedLibrary("p256m"), .linkedLibrary("pthread"),
|
||||
]
|
||||
#else
|
||||
let native: Target = .binaryTarget(name: "CDModemSSH", path: "../../build-apple/DModemSSHNative.xcframework")
|
||||
let nativeLinking: [LinkerSetting] = []
|
||||
#endif
|
||||
|
||||
let package = Package(
|
||||
name: "DModemSSH",
|
||||
platforms: [.macOS(.v12), .iOS(.v15)],
|
||||
products: [.library(name: "DModemSSH", targets: ["DModemSSH"])],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-nio.git", from: "2.65.0"),
|
||||
.package(url: "https://github.com/apple/swift-nio-ssh.git", from: "0.9.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(name: "DModemSSH", dependencies: [
|
||||
.product(name: "NIOCore", package: "swift-nio"),
|
||||
.product(name: "NIOPosix", package: "swift-nio"),
|
||||
.product(name: "NIOSSH", package: "swift-nio-ssh"),
|
||||
]),
|
||||
native,
|
||||
.target(name: "DModemSSH", dependencies: ["CDModemSSH"], linkerSettings: nativeLinking),
|
||||
.testTarget(name: "DModemSSHTests", dependencies: ["DModemSSH"]),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,4 @@
|
||||
module CDModemSSH [system] {
|
||||
header "../../../../native-ssh/include/dmodemssh.h"
|
||||
export *
|
||||
}
|
||||
@@ -1,21 +1,21 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
import CDModemSSH
|
||||
import Foundation
|
||||
import NIOCore
|
||||
import NIOPosix
|
||||
import NIOSSH
|
||||
|
||||
/// An SSH login's interactive shell: the host's key checked by the caller
|
||||
/// ([verifyHostKey], its OpenSSH form), the user logged in by password
|
||||
/// ([askPassword], asked again when one is refused, three times at most),
|
||||
/// a pty of [term] in the screen's size and a shell on it. What the
|
||||
/// server says (stdout and stderr) goes to [onData]; [write] sends what
|
||||
/// is typed; [resize] the window's new size. [onClose] once, with why
|
||||
/// (nil when it was asked to).
|
||||
/// An SSH login's interactive shell, on libdmodemssh (native-ssh, on
|
||||
/// libssh): the host's key checked by the caller ([verifyHostKey], its
|
||||
/// OpenSSH form), the user logged in by a private key ([privateKey], when
|
||||
/// one is given), else by password ([askPassword], asked again when one is
|
||||
/// refused, three times at most) or the server's questions
|
||||
/// ([askQuestions], keyboard-interactive); a pty of [term] in the
|
||||
/// screen's size and a shell on it. What the server says (stdout and
|
||||
/// stderr) goes to [onData]; [write] sends what is typed; [resize] the
|
||||
/// window's new size. [onClose] once, with why (nil when it was asked to).
|
||||
///
|
||||
/// The callbacks are made on the connection's own thread: hop to the
|
||||
/// main one to touch views. Host keys: Ed25519 and ECDSA (SwiftNIO SSH
|
||||
/// has no RSA).
|
||||
/// main one to touch views. Host keys and the user's: Ed25519, ECDSA and
|
||||
/// RSA.
|
||||
public final class SSHShell: @unchecked Sendable {
|
||||
public let host: String
|
||||
public let port: Int
|
||||
@@ -29,17 +29,25 @@ public final class SSHShell: @unchecked Sendable {
|
||||
/// the user's password, asked ("" when it's the first time, else why
|
||||
/// the last was refused): call back with nil to give up
|
||||
public var askPassword: (String, @escaping (String?) -> Void) -> Void = { _, done in done(nil) }
|
||||
/// the server's questions (keyboard-interactive): its instruction and
|
||||
/// each question with whether its answer may be shown; call back with
|
||||
/// the answers, or nil to give up. Unset: passwords are asked by
|
||||
/// [askPassword] instead
|
||||
public var askQuestions: ((String, [(String, Bool)], @escaping ([String]?) -> Void) -> Void)?
|
||||
/// a private key's text (OpenSSH's or PEM) to log in with first, and
|
||||
/// its passphrase
|
||||
public var privateKey: (key: String, passphrase: String?)?
|
||||
|
||||
private var cols: Int
|
||||
private var rows: Int
|
||||
/// (SwiftNIO's shared threads: a shell's owner may let go of it on one)
|
||||
private let group = MultiThreadedEventLoopGroup.singleton
|
||||
private var channel: Channel?
|
||||
private var shell: Channel?
|
||||
private let lock = NSLock()
|
||||
private var closed = false
|
||||
private var closing = false
|
||||
private var exitStatus: Int?
|
||||
private let s: OpaquePointer?
|
||||
private var shell: Int32 = 0
|
||||
private var started = false
|
||||
private var asked = false
|
||||
private var exitStatus = 0
|
||||
private var triedKey = false
|
||||
private var asks = 0
|
||||
|
||||
/// a shell to log in to: nothing is done until [connect]
|
||||
public init(host: String, port: Int = 22, user: String, term: String = "xterm-256color", cols: Int = 80, rows: Int = 24) {
|
||||
@@ -49,265 +57,151 @@ public final class SSHShell: @unchecked Sendable {
|
||||
self.term = term
|
||||
self.cols = cols
|
||||
self.rows = rows
|
||||
s = dmc_ssh_new(host, Int32(port), user)
|
||||
}
|
||||
|
||||
/// the connection freed
|
||||
deinit {
|
||||
// (its thread holds the shell until the connection's over)
|
||||
if let s { dmc_ssh_free(s) }
|
||||
}
|
||||
|
||||
/// connect, log in and start the shell, on the connection's thread
|
||||
public func connect() {
|
||||
let auth = PasswordAuth(user: user) { [weak self] why, done in
|
||||
guard let self else { return done(nil) }
|
||||
self.askPassword(why, done)
|
||||
}
|
||||
let keys = HostKeyCheck { [weak self] key, done in
|
||||
guard let self else { return done(false) }
|
||||
self.verifyHostKey(key, done)
|
||||
}
|
||||
let bootstrap = ClientBootstrap(group: group)
|
||||
.connectTimeout(.seconds(20))
|
||||
.channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
|
||||
.channelInitializer { ch in
|
||||
ch.eventLoop.makeCompletedFuture {
|
||||
let ssh = NIOSSHHandler(
|
||||
role: .client(.init(userAuthDelegate: auth, serverAuthDelegate: keys)),
|
||||
allocator: ch.allocator, inboundChildChannelInitializer: nil)
|
||||
try ch.pipeline.syncOperations.addHandlers([ssh, ErrorCatcher { [weak self] e in self?.failed(e) }])
|
||||
guard let s else { return onClose("could not start SSH") }
|
||||
guard !started else { return }
|
||||
started = true
|
||||
let t = Thread { self.run(s) }
|
||||
t.name = "ssh-\(host)"
|
||||
t.start()
|
||||
}
|
||||
|
||||
/// the connection's life: each event acted on until it's over
|
||||
private func run(_ s: OpaquePointer) {
|
||||
var ev = dmc_ssh_event()
|
||||
while dmc_ssh_poll(s, 1000, &ev) >= 0 {
|
||||
if ev.type == 0 { continue }
|
||||
let data: Data? = ev.data.map { Data(bytes: $0, count: Int(ev.len)) }
|
||||
let text = data.map { String(decoding: $0, as: UTF8.self) }
|
||||
let type = Int(ev.type)
|
||||
ev.type = 0
|
||||
switch type {
|
||||
case DMC_SSH_EV_HOSTKEY:
|
||||
verifyHostKey(text ?? "") { ok in dmc_ssh_trust(s, ok ? 1 : 0, 0) }
|
||||
case DMC_SSH_EV_AUTH:
|
||||
login(s, methods: Int(ev.value), why: text ?? "")
|
||||
case DMC_SSH_EV_PROMPTS:
|
||||
questions(s, count: Int(ev.value))
|
||||
case DMC_SSH_EV_READY:
|
||||
let (c, r) = lock.withLock { (cols, rows) }
|
||||
let ch = dmc_ssh_shell(s, term, Int32(c), Int32(r), 0)
|
||||
lock.withLock { shell = ch }
|
||||
case DMC_SSH_EV_OPEN:
|
||||
if ev.value == 0 { dmc_ssh_disconnect(s) }
|
||||
case DMC_SSH_EV_DATA:
|
||||
if ev.channel == lock.withLock({ shell }), let data { onData(data) }
|
||||
case DMC_SSH_EV_EXIT:
|
||||
if ev.channel == lock.withLock({ shell }) { exitStatus = Int(ev.value) }
|
||||
case DMC_SSH_EV_CLOSE:
|
||||
// (the shell's over: so is the connection)
|
||||
if ev.channel == lock.withLock({ shell }) {
|
||||
lock.withLock { shell = 0 }
|
||||
dmc_ssh_disconnect(s)
|
||||
}
|
||||
}
|
||||
bootstrap.connect(host: host, port: port).flatMap { [weak self] (ch: Channel) -> EventLoopFuture<Channel> in
|
||||
guard let self else { return ch.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel) }
|
||||
self.lock.withLock { self.channel = ch }
|
||||
ch.closeFuture.whenComplete { [weak self] _ in self?.finish(nil) }
|
||||
return ch.pipeline.handler(type: NIOSSHHandler.self).flatMap { ssh in
|
||||
let p = ch.eventLoop.makePromise(of: Channel.self)
|
||||
ssh.createChannel(p) { child, type in
|
||||
guard type == .session else {
|
||||
return child.eventLoop.makeFailedFuture(SSHShellError.unexpectedChannel)
|
||||
}
|
||||
return child.setOption(ChannelOptions.allowRemoteHalfClosure, value: true).flatMap {
|
||||
child.pipeline.addHandler(ShellHandler(owner: self))
|
||||
}
|
||||
case DMC_SSH_EV_INCOMING:
|
||||
dmc_ssh_close(s, ev.channel)
|
||||
case DMC_SSH_EV_CLOSED:
|
||||
let byUser = lock.withLock { asked }
|
||||
if text != nil {
|
||||
onClose(text)
|
||||
} else if byUser {
|
||||
onClose(nil)
|
||||
} else if exitStatus != 0 {
|
||||
onClose("the shell exited with status \(exitStatus)")
|
||||
} else {
|
||||
onClose("Connection closed")
|
||||
}
|
||||
return p.futureResult
|
||||
return
|
||||
default:
|
||||
break
|
||||
}
|
||||
}.flatMap { [weak self] (child: Channel) -> EventLoopFuture<Void> in
|
||||
guard let self else { return child.eventLoop.makeSucceededVoidFuture() }
|
||||
self.lock.withLock { self.shell = child }
|
||||
let (c, r) = self.lock.withLock { (self.cols, self.rows) }
|
||||
let pty = SSHChannelRequestEvent.PseudoTerminalRequest(
|
||||
wantReply: true, term: self.term, terminalCharacterWidth: c, terminalRowHeight: r,
|
||||
terminalPixelWidth: 0, terminalPixelHeight: 0, terminalModes: SSHTerminalModes([:]))
|
||||
return child.triggerUserOutboundEvent(pty).flatMap {
|
||||
child.triggerUserOutboundEvent(SSHChannelRequestEvent.ShellRequest(wantReply: true))
|
||||
}
|
||||
}
|
||||
|
||||
/// the next login: the key first, then the server's questions or a
|
||||
/// password (three times at most)
|
||||
private func login(_ s: OpaquePointer, methods: Int, why: String) {
|
||||
if let k = privateKey, !triedKey, methods & DMC_SSH_AUTH_PUBLICKEY != 0 {
|
||||
triedKey = true
|
||||
if dmc_ssh_auth_key(s, k.key, k.passphrase) == 0 { return }
|
||||
}
|
||||
asks += 1
|
||||
let interactive = methods & DMC_SSH_AUTH_INTERACTIVE != 0
|
||||
let password = methods & DMC_SSH_AUTH_PASSWORD != 0
|
||||
if asks > 3 {
|
||||
dmc_ssh_auth_cancel(s)
|
||||
} else if interactive && (askQuestions != nil || !password) {
|
||||
dmc_ssh_auth_interactive(s)
|
||||
} else if password {
|
||||
askPassword(asks == 1 ? "" : (why.isEmpty ? "The password was not accepted" : why)) { pw in
|
||||
if let pw { dmc_ssh_auth_password(s, pw) } else { dmc_ssh_auth_cancel(s) }
|
||||
}
|
||||
}.whenFailure { [weak self] e in self?.failed(e) }
|
||||
} else {
|
||||
dmc_ssh_auth_cancel(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// a round of the server's questions put to the user
|
||||
private func questions(_ s: OpaquePointer, count: Int) {
|
||||
if count == 0 { return dmc_ssh_answered(s) }
|
||||
var qs: [(String, Bool)] = []
|
||||
for i in 0..<count {
|
||||
var echo: Int32 = 0
|
||||
qs.append((String(cString: dmc_ssh_prompt(s, Int32(i), &echo)), echo != 0))
|
||||
}
|
||||
let instruction = String(cString: dmc_ssh_instruction(s))
|
||||
let answer: ([String]?) -> Void = { a in
|
||||
guard let a else { return dmc_ssh_auth_cancel(s) }
|
||||
for (i, x) in a.enumerated() { dmc_ssh_answer(s, Int32(i), x) }
|
||||
dmc_ssh_answered(s)
|
||||
}
|
||||
if let askQuestions {
|
||||
askQuestions(instruction, qs, answer)
|
||||
} else {
|
||||
askPassword(asks <= 1 ? "" : "The password was not accepted") { pw in answer(pw.map { [$0] }) }
|
||||
}
|
||||
}
|
||||
|
||||
/// what's typed, to the shell
|
||||
public func write(_ data: Data) {
|
||||
guard let s = lock.withLock({ shell }), !data.isEmpty else { return }
|
||||
var b = s.allocator.buffer(capacity: data.count)
|
||||
b.writeBytes(data)
|
||||
s.writeAndFlush(SSHChannelData(type: .channel, data: .byteBuffer(b)), promise: nil)
|
||||
guard let s, !data.isEmpty else { return }
|
||||
let ch = lock.withLock { shell }
|
||||
guard ch > 0 else { return }
|
||||
data.withUnsafeBytes { b in
|
||||
_ = dmc_ssh_write(s, ch, b.baseAddress!.assumingMemoryBound(to: CChar.self), Int32(b.count))
|
||||
}
|
||||
}
|
||||
|
||||
/// the screen's new size, to the server
|
||||
public func resize(cols: Int, rows: Int) {
|
||||
let s: Channel? = lock.withLock {
|
||||
guard let s else { return }
|
||||
let ch: Int32? = lock.withLock {
|
||||
guard cols != self.cols || rows != self.rows else { return nil }
|
||||
self.cols = cols
|
||||
self.rows = rows
|
||||
return shell
|
||||
}
|
||||
s?.triggerUserOutboundEvent(SSHChannelRequestEvent.WindowChangeRequest(
|
||||
terminalCharacterWidth: cols, terminalRowHeight: rows, terminalPixelWidth: 0, terminalPixelHeight: 0), promise: nil)
|
||||
if let ch, ch > 0 { dmc_ssh_resize(s, ch, Int32(cols), Int32(rows)) }
|
||||
}
|
||||
|
||||
/// the connection closed by the user
|
||||
public func close() {
|
||||
let ch: Channel? = lock.withLock {
|
||||
closing = true
|
||||
return channel
|
||||
}
|
||||
if let ch {
|
||||
ch.close(promise: nil)
|
||||
guard let s else { return }
|
||||
lock.withLock { asked = true }
|
||||
if started {
|
||||
dmc_ssh_disconnect(s)
|
||||
} else {
|
||||
finish(nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// the server's data, to [onData]
|
||||
fileprivate func received(_ data: Data) { onData(data) }
|
||||
|
||||
/// the shell's exit status, kept for [onClose]
|
||||
fileprivate func exited(_ status: Int) { lock.withLock { exitStatus = status } }
|
||||
|
||||
/// the shell's channel closed: the connection is closed too
|
||||
fileprivate func shellClosed() {
|
||||
// (the shell's over: so is the connection)
|
||||
lock.withLock { channel }?.close(promise: nil)
|
||||
}
|
||||
|
||||
/// an error: [onClose] told why, the connection closed
|
||||
fileprivate func failed(_ e: Error) {
|
||||
finish(Self.describe(e))
|
||||
lock.withLock { channel }?.close(promise: nil)
|
||||
}
|
||||
|
||||
/// [onClose] called, once, with why
|
||||
private func finish(_ why: String?) {
|
||||
let (first, asked, status): (Bool, Bool, Int?) = lock.withLock {
|
||||
defer { closed = true }
|
||||
return (!closed, closing, exitStatus)
|
||||
}
|
||||
guard first else { return }
|
||||
if asked {
|
||||
onClose(nil)
|
||||
} else if let why {
|
||||
onClose(why)
|
||||
} else if let status, status != 0 {
|
||||
onClose("the shell exited with status \(status)")
|
||||
} else {
|
||||
onClose("Connection closed")
|
||||
}
|
||||
}
|
||||
|
||||
/// an error in words for the user
|
||||
static func describe(_ e: Error) -> String {
|
||||
switch e {
|
||||
case SSHShellError.hostKeyRefused: return "the host's key was not accepted"
|
||||
case SSHShellError.noPassword: return "not logged in"
|
||||
case SSHShellError.unexpectedChannel: return "the server opened an unexpected channel"
|
||||
default: break
|
||||
}
|
||||
if let n = e as? NIOSSHError {
|
||||
switch n.type {
|
||||
case .invalidHostKeyForKeyExchange, .keyExchangeNegotiationFailure:
|
||||
return "no host key or key exchange in common (this app has Ed25519 and ECDSA, not RSA)"
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
if e is NIOConnectionError || e is IOError { return "could not connect: \(e)" }
|
||||
return "\(e)"
|
||||
}
|
||||
}
|
||||
|
||||
public enum SSHShellError: Error {
|
||||
case hostKeyRefused, noPassword, unexpectedChannel
|
||||
}
|
||||
|
||||
/// the password, asked; again (with why) when the server refuses it, three times at most
|
||||
private final class PasswordAuth: NIOSSHClientUserAuthenticationDelegate {
|
||||
let user: String
|
||||
let ask: (String, @escaping (String?) -> Void) -> Void
|
||||
var tries = 0
|
||||
|
||||
/// asks [ask] for the password for [user]
|
||||
init(user: String, ask: @escaping (String, @escaping (String?) -> Void) -> Void) {
|
||||
self.user = user
|
||||
self.ask = ask
|
||||
}
|
||||
|
||||
/// the next password offered, or a failure once there are none
|
||||
func nextAuthenticationType(
|
||||
availableMethods: NIOSSHAvailableUserAuthenticationMethods,
|
||||
nextChallengePromise: EventLoopPromise<NIOSSHUserAuthenticationOffer?>
|
||||
) {
|
||||
guard availableMethods.contains(.password) else {
|
||||
nextChallengePromise.fail(SSHShellError.noPassword)
|
||||
return
|
||||
}
|
||||
guard tries < 3 else {
|
||||
nextChallengePromise.fail(SSHShellError.noPassword)
|
||||
return
|
||||
}
|
||||
tries += 1
|
||||
let user = self.user
|
||||
ask(tries == 1 ? "" : "The password was not accepted") { pw in
|
||||
guard let pw else {
|
||||
nextChallengePromise.fail(SSHShellError.noPassword)
|
||||
return
|
||||
}
|
||||
nextChallengePromise.succeed(NIOSSHUserAuthenticationOffer(
|
||||
username: user, serviceName: "", offer: .password(.init(password: pw))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// the host's key, as OpenSSH writes it, to the caller to accept or not
|
||||
private final class HostKeyCheck: NIOSSHClientServerAuthenticationDelegate {
|
||||
let verify: (String, @escaping (Bool) -> Void) -> Void
|
||||
|
||||
/// asks [verify] about each host key
|
||||
init(verify: @escaping (String, @escaping (Bool) -> Void) -> Void) {
|
||||
self.verify = verify
|
||||
}
|
||||
|
||||
/// the host's key, to the caller to accept or refuse
|
||||
func validateHostKey(hostKey: NIOSSHPublicKey, validationCompletePromise: EventLoopPromise<Void>) {
|
||||
verify(String(openSSHPublicKey: hostKey)) { ok in
|
||||
if ok {
|
||||
validationCompletePromise.succeed(())
|
||||
} else {
|
||||
validationCompletePromise.fail(SSHShellError.hostKeyRefused)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// the shell's channel: its data (stdout and stderr) to the owner, its exit status kept
|
||||
private final class ShellHandler: ChannelInboundHandler {
|
||||
typealias InboundIn = SSHChannelData
|
||||
|
||||
private weak var owner: SSHShell?
|
||||
|
||||
/// for [owner]'s shell
|
||||
init(owner: SSHShell) {
|
||||
self.owner = owner
|
||||
}
|
||||
|
||||
/// the server's data, to the owner
|
||||
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
let d = unwrapInboundIn(data)
|
||||
guard case .byteBuffer(var b) = d.data, let bytes = b.readBytes(length: b.readableBytes) else { return }
|
||||
owner?.received(Data(bytes))
|
||||
}
|
||||
|
||||
/// the exit status kept; the shell closed when the server's output ends
|
||||
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
|
||||
if let s = event as? SSHChannelRequestEvent.ExitStatus {
|
||||
owner?.exited(s.exitStatus)
|
||||
} else if event is ChannelEvent, case .inputClosed = event as! ChannelEvent {
|
||||
context.close(promise: nil)
|
||||
}
|
||||
context.fireUserInboundEventTriggered(event)
|
||||
}
|
||||
|
||||
/// the shell's channel gone: the owner told
|
||||
func channelInactive(context: ChannelHandlerContext) {
|
||||
owner?.shellClosed()
|
||||
context.fireChannelInactive()
|
||||
}
|
||||
|
||||
/// the error to the owner, the channel closed
|
||||
func errorCaught(context: ChannelHandlerContext, error: Error) {
|
||||
owner?.failed(error)
|
||||
context.close(promise: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// the connection's errors (a refused host key, a failed login) to the owner
|
||||
private final class ErrorCatcher: ChannelInboundHandler {
|
||||
typealias InboundIn = Any
|
||||
let caught: (Error) -> Void
|
||||
|
||||
/// [caught] told of each error
|
||||
init(caught: @escaping (Error) -> Void) {
|
||||
self.caught = caught
|
||||
}
|
||||
|
||||
/// the error to the owner, the connection closed
|
||||
func errorCaught(context: ChannelHandlerContext, error: Error) {
|
||||
caught(error)
|
||||
context.close(promise: nil)
|
||||
}
|
||||
}
|
||||
+74
-1
@@ -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 <name> <system> <sdk> <arch> <min>: $OUT/<name>/ssh-<arch>.o
|
||||
ssh_arch() {
|
||||
name=$1 system=$2 sdk=$3 arch=$4 min=$5
|
||||
dir=$OUT/$name/ssh-$arch
|
||||
echo "== SSH $name ($sdk, $arch)"
|
||||
set -- -S "$ROOT/native-ssh" -B "$dir" -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_OSX_SYSROOT="$sdk" \
|
||||
-DCMAKE_OSX_ARCHITECTURES="$arch" \
|
||||
-DCMAKE_OSX_DEPLOYMENT_TARGET="$min"
|
||||
[ "$system" = iOS ] && set -- "$@" -DCMAKE_SYSTEM_NAME=iOS
|
||||
cmake "$@"
|
||||
cmake --build "$dir" --target dmodemssh
|
||||
objs=$dir/objs
|
||||
rm -rf "$objs"
|
||||
mkdir -p "$objs"
|
||||
# (each archive's objects apart: their names repeat between them)
|
||||
i=0
|
||||
for a in "$dir/libdmodemssh.a" "$dir/dmodem-libssh/lib/libssh.a" \
|
||||
"$dir"/dmodem-libssh/lib/libmbed*.a "$dir/dmodem-libssh/lib/libeverest.a" \
|
||||
"$dir/dmodem-libssh/lib/libp256m.a"; do
|
||||
i=$((i + 1))
|
||||
mkdir -p "$objs/$i"
|
||||
(cd "$objs/$i" && ar x "$a")
|
||||
done
|
||||
printf '_dmc_ssh_*\n' > "$dir/exports"
|
||||
xcrun ld -r -arch "$arch" -exported_symbols_list "$dir/exports" \
|
||||
"$objs"/*/*.o -o "$OUT/$name/ssh-$arch.o"
|
||||
}
|
||||
|
||||
# ssh_slice <name> <system> <sdk> <min> <arch>...: $OUT/<name>/libDModemSSHNative.a
|
||||
ssh_slice() {
|
||||
name=$1 system=$2 sdk=$3 min=$4
|
||||
shift 4
|
||||
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" <<MAP
|
||||
module CDModemSSH {
|
||||
header "dmodemssh.h"
|
||||
export *
|
||||
}
|
||||
MAP
|
||||
|
||||
rm -rf "$OUT/DModemSSHNative.xcframework"
|
||||
xcodebuild -create-xcframework \
|
||||
-library "$OUT/ios/libDModemSSHNative.a" -headers "$sinc" \
|
||||
-library "$OUT/ios-simulator/libDModemSSHNative.a" -headers "$sinc" \
|
||||
-library "$OUT/macos/libDModemSSHNative.a" -headers "$sinc" \
|
||||
-output "$OUT/DModemSSHNative.xcframework"
|
||||
echo "built $OUT/DModemSSHNative.xcframework"
|
||||
@@ -0,0 +1,32 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Copyright (C) 2026 Neo-Desktop
|
||||
#
|
||||
# libdmodemssh: the apps' SSH client (dmodemssh.h) on libssh 0.11 and
|
||||
# mbedTLS, both built here from their release tarballs (checked by hash).
|
||||
# The same engine as D-Modem/gui's ssh/: Android loads it through JNI
|
||||
# (app/src/main/cpp), iOS as ios/build-native.sh's DModemSSHNative
|
||||
# XCFramework, and here on the build host for its tests:
|
||||
#
|
||||
# cmake -S native-ssh -B build-ssh && cmake --build build-ssh
|
||||
# DMODEM_SSH_TEST=host:port:user:password build-ssh/dmodemssh_test
|
||||
cmake_minimum_required(VERSION 3.22)
|
||||
project(dmodemssh LANGUAGES C)
|
||||
|
||||
include(${CMAKE_CURRENT_LIST_DIR}/cmake/BundledLibssh.cmake)
|
||||
|
||||
add_library(dmodemssh STATIC src/dmodemssh.c)
|
||||
target_include_directories(dmodemssh PUBLIC include)
|
||||
target_link_libraries(dmodemssh PUBLIC dmodem_libssh)
|
||||
set_target_properties(dmodemssh PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
if(NOT WIN32)
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(dmodemssh PUBLIC Threads::Threads)
|
||||
endif()
|
||||
target_compile_options(dmodemssh PRIVATE -Wall -Wextra -Wshadow)
|
||||
|
||||
if(NOT ANDROID AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS")
|
||||
enable_testing()
|
||||
add_executable(dmodemssh_test test/dmodemssh_test.c)
|
||||
target_link_libraries(dmodemssh_test PRIVATE dmodemssh)
|
||||
add_test(NAME dmodemssh COMMAND dmodemssh_test)
|
||||
endif()
|
||||
@@ -0,0 +1,95 @@
|
||||
# libssh on mbedTLS, both static, built from their release tarballs
|
||||
# (checked by hash), as the target dmodem_libssh.
|
||||
include(FetchContent)
|
||||
include(ExternalProject)
|
||||
|
||||
set(DMODEM_MBEDTLS_URL https://github.com/Mbed-TLS/mbedtls/releases/download/mbedtls-3.6.4/mbedtls-3.6.4.tar.bz2)
|
||||
set(DMODEM_MBEDTLS_SHA256 ec35b18a6c593cf98c3e30db8b98ff93e8940a8c4e690e66b41dfc011d678110)
|
||||
set(DMODEM_LIBSSH_URL https://www.libssh.org/files/0.11/libssh-0.11.3.tar.xz)
|
||||
set(DMODEM_LIBSSH_SHA256 7d8a1361bb094ec3f511964e78a5a4dba689b5986e112afabe4f4d0d6c6125c3)
|
||||
|
||||
set(_prefix ${CMAKE_BINARY_DIR}/dmodem-libssh)
|
||||
set(_args
|
||||
-DCMAKE_BUILD_TYPE=Release
|
||||
-DCMAKE_INSTALL_PREFIX=${_prefix}
|
||||
-DCMAKE_INSTALL_LIBDIR=lib
|
||||
-DCMAKE_POSITION_INDEPENDENT_CODE=ON
|
||||
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
|
||||
-DCMAKE_MSVC_RUNTIME_LIBRARY=${CMAKE_MSVC_RUNTIME_LIBRARY}
|
||||
-DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES}
|
||||
-DCMAKE_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET}
|
||||
-DCMAKE_OSX_SYSROOT=${CMAKE_OSX_SYSROOT})
|
||||
if(CMAKE_TOOLCHAIN_FILE)
|
||||
list(APPEND _args -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE})
|
||||
endif()
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "iOS")
|
||||
list(APPEND _args -DCMAKE_SYSTEM_NAME=iOS)
|
||||
endif()
|
||||
if(ANDROID)
|
||||
list(APPEND _args -DANDROID_ABI=${ANDROID_ABI} -DANDROID_PLATFORM=${ANDROID_PLATFORM})
|
||||
endif()
|
||||
if(CMAKE_MAKE_PROGRAM)
|
||||
list(APPEND _args -DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM})
|
||||
endif()
|
||||
string(REPLACE ";" "|" _archs "${CMAKE_OSX_ARCHITECTURES}")
|
||||
list(TRANSFORM _args REPLACE "^-DCMAKE_OSX_ARCHITECTURES=.*" "-DCMAKE_OSX_ARCHITECTURES=${_archs}")
|
||||
|
||||
if(WIN32)
|
||||
set(_mbed_libs mbedcrypto.lib mbedx509.lib mbedtls.lib everest.lib p256m.lib)
|
||||
set(_ssh_lib ssh.lib)
|
||||
if(MINGW)
|
||||
set(_mbed_libs libmbedcrypto.a libmbedx509.a libmbedtls.a libeverest.a libp256m.a)
|
||||
set(_ssh_lib libssh.a)
|
||||
endif()
|
||||
else()
|
||||
set(_mbed_libs libmbedcrypto.a libmbedx509.a libmbedtls.a libeverest.a libp256m.a)
|
||||
set(_ssh_lib libssh.a)
|
||||
endif()
|
||||
list(TRANSFORM _mbed_libs PREPEND ${_prefix}/lib/ OUTPUT_VARIABLE _mbed_paths)
|
||||
|
||||
ExternalProject_Add(dmodem_mbedtls
|
||||
URL ${DMODEM_MBEDTLS_URL}
|
||||
URL_HASH SHA256=${DMODEM_MBEDTLS_SHA256}
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
|
||||
PATCH_COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_LIST_DIR}/PatchMbedtls.cmake
|
||||
LIST_SEPARATOR |
|
||||
CMAKE_ARGS ${_args} -DENABLE_TESTING=OFF -DENABLE_PROGRAMS=OFF
|
||||
-DUSE_SHARED_MBEDTLS_LIBRARY=OFF -DMBEDTLS_FATAL_WARNINGS=OFF
|
||||
BUILD_BYPRODUCTS ${_mbed_paths})
|
||||
|
||||
# (Bionic has no S_IWRITE, the old name libssh uses)
|
||||
set(_ssh_args)
|
||||
if(ANDROID)
|
||||
list(APPEND _ssh_args -DCMAKE_C_FLAGS=-DS_IWRITE=S_IWUSR)
|
||||
endif()
|
||||
|
||||
ExternalProject_Add(dmodem_libssh_build
|
||||
URL ${DMODEM_LIBSSH_URL}
|
||||
URL_HASH SHA256=${DMODEM_LIBSSH_SHA256}
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
|
||||
DEPENDS dmodem_mbedtls
|
||||
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_EXAMPLES=OFF -DUNIT_TESTING=OFF -DCLIENT_TESTING=OFF
|
||||
-DWITH_NACL=OFF -DWITH_SYMBOL_VERSIONING=OFF
|
||||
BUILD_BYPRODUCTS ${_prefix}/lib/${_ssh_lib})
|
||||
|
||||
file(MAKE_DIRECTORY ${_prefix}/include)
|
||||
add_library(dmodem_libssh INTERFACE)
|
||||
add_dependencies(dmodem_libssh dmodem_libssh_build)
|
||||
target_include_directories(dmodem_libssh INTERFACE ${_prefix}/include)
|
||||
target_compile_definitions(dmodem_libssh INTERFACE LIBSSH_STATIC=1)
|
||||
target_link_libraries(dmodem_libssh INTERFACE ${_prefix}/lib/${_ssh_lib} ${_mbed_paths})
|
||||
if(WIN32)
|
||||
target_link_libraries(dmodem_libssh INTERFACE ws2_32 iphlpapi bcrypt shell32 advapi32)
|
||||
# (MinGW's libssh locks with winpthreads)
|
||||
if(MINGW)
|
||||
target_link_libraries(dmodem_libssh INTERFACE pthread)
|
||||
endif()
|
||||
elseif(UNIX)
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(dmodem_libssh INTERFACE Threads::Threads)
|
||||
endif()
|
||||
@@ -0,0 +1,24 @@
|
||||
# mbedTLS's config with threading on, as libssh wants it: its own
|
||||
# pthread mutexes, or (Windows) libssh's given through threading_alt.h.
|
||||
# Run in mbedTLS's source tree by BundledLibssh.cmake.
|
||||
set(_config include/mbedtls/mbedtls_config.h)
|
||||
file(READ ${_config} _text)
|
||||
if(NOT _text MATCHES "D-Modem: threading")
|
||||
file(APPEND ${_config} "
|
||||
/* D-Modem: threading, for libssh */
|
||||
#define MBEDTLS_THREADING_C
|
||||
#if defined(_WIN32)
|
||||
#define MBEDTLS_THREADING_ALT
|
||||
#else
|
||||
#define MBEDTLS_THREADING_PTHREAD
|
||||
#endif
|
||||
")
|
||||
endif()
|
||||
file(WRITE include/mbedtls/threading_alt.h "/* D-Modem: libssh's mutexes (a pointer each) */
|
||||
#ifndef DMODEM_THREADING_ALT_H
|
||||
#define DMODEM_THREADING_ALT_H
|
||||
typedef struct mbedtls_threading_mutex_t {
|
||||
void *mutex;
|
||||
} mbedtls_threading_mutex_t;
|
||||
#endif
|
||||
")
|
||||
@@ -0,0 +1,181 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 Neo-Desktop
|
||||
*
|
||||
* dmodemssh.h - D-Modem's SSH client, on libssh: the one engine every
|
||||
* app has (the desktops', iOS's, and Android's through JNI), so that
|
||||
* each has the same SSH.
|
||||
*
|
||||
* A connection (dmc_ssh) is driven by one thread that calls
|
||||
* dmc_ssh_poll() in a loop and acts on the events it hands back: the
|
||||
* server's key to trust or not, a login method to choose, a
|
||||
* keyboard-interactive round to answer, a channel's data. Every other
|
||||
* call may come from any thread (a lock is taken): what is typed, a
|
||||
* window's new size, the answers.
|
||||
*
|
||||
* What it has: host keys checked by the caller (and in OpenSSH's
|
||||
* known_hosts when asked); logins by password, keyboard-interactive, a
|
||||
* private key (OpenSSH's, PEM), the system's agent, or OpenSSH's own
|
||||
* keys and agent at once (ssh's default); ~/.ssh/config when asked; Ed25519,
|
||||
* ECDSA and RSA keys; a shell on a pty, a command, direct TCP channels
|
||||
* (ssh -L and -D), remote listens (ssh -R) and the server's
|
||||
* agent channels (ssh -A) handed to the caller as channels.
|
||||
*
|
||||
* This file and dmodemssh.c are the same in D-Modem/gui (ssh/) and
|
||||
* D-Modem/app (native-ssh/): change both.
|
||||
*/
|
||||
#ifndef DMODEMSSH_H
|
||||
#define DMODEMSSH_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct dmc_ssh dmc_ssh;
|
||||
|
||||
/* what dmc_ssh_poll() hands back */
|
||||
enum {
|
||||
DMC_SSH_EV_HOSTKEY = 1, /* the server's key: data is its OpenSSH line
|
||||
("ssh-ed25519 AAAA..."), value a
|
||||
DMC_SSH_HOST_*; answer dmc_ssh_trust() */
|
||||
DMC_SSH_EV_AUTH, /* a login method wanted: value is the
|
||||
DMC_SSH_AUTH_* the server takes, data why
|
||||
the last failed ("" the first time);
|
||||
answer one dmc_ssh_auth_*() */
|
||||
DMC_SSH_EV_PROMPTS, /* the server's questions (keyboard-
|
||||
interactive): value how many, data the
|
||||
round's name; read them with
|
||||
dmc_ssh_prompt(), answer each with
|
||||
dmc_ssh_answer(), then dmc_ssh_answered() */
|
||||
DMC_SSH_EV_READY, /* logged in: data the server's banner, if any */
|
||||
DMC_SSH_EV_OPEN, /* a channel opened (value 1) or refused
|
||||
(value 0, data why) */
|
||||
DMC_SSH_EV_DATA, /* a channel's data (value 1: its stderr) */
|
||||
DMC_SSH_EV_EOF, /* a channel's end of data */
|
||||
DMC_SSH_EV_EXIT, /* a command's exit status (value), or the
|
||||
signal that ended it (data) */
|
||||
DMC_SSH_EV_CLOSE, /* a channel closed: its number is free */
|
||||
DMC_SSH_EV_INCOMING, /* a channel the server opened, open now:
|
||||
value DMC_SSH_IN_AGENT, or the remote
|
||||
listen's port (data: who connected) */
|
||||
DMC_SSH_EV_LISTEN, /* a remote listen (channel: its request's
|
||||
number) answered: value the port bound,
|
||||
-1 refused */
|
||||
DMC_SSH_EV_CLOSED /* the connection over: data why (NULL when
|
||||
dmc_ssh_disconnect() asked) */
|
||||
};
|
||||
|
||||
typedef struct dmc_ssh_event {
|
||||
int type;
|
||||
int channel; /* the channel it's about (1 and up), or 0 */
|
||||
int value;
|
||||
const char *data; /* until the next dmc_ssh_poll() */
|
||||
int len;
|
||||
} dmc_ssh_event;
|
||||
|
||||
/* the server's key against OpenSSH's known_hosts (when the
|
||||
"knownhosts" option was given) */
|
||||
enum {
|
||||
DMC_SSH_HOST_UNCHECKED = 0, DMC_SSH_HOST_KNOWN, DMC_SSH_HOST_NEW,
|
||||
DMC_SSH_HOST_CHANGED, DMC_SSH_HOST_OTHER_TYPE
|
||||
};
|
||||
|
||||
/* the login methods the server takes */
|
||||
enum {
|
||||
DMC_SSH_AUTH_PASSWORD = 1, DMC_SSH_AUTH_PUBLICKEY = 2,
|
||||
DMC_SSH_AUTH_INTERACTIVE = 4
|
||||
};
|
||||
|
||||
/* a server-opened channel that is the agent's (ssh -A) */
|
||||
enum { DMC_SSH_IN_AGENT = -1 };
|
||||
|
||||
/* a connection to make to user@host:port (nothing done until polled) */
|
||||
dmc_ssh *dmc_ssh_new(const char *host, int port, const char *user);
|
||||
/* the connection dropped (if it's up) and freed */
|
||||
void dmc_ssh_free(dmc_ssh *s);
|
||||
/* an option, before the first poll: 0, or -1 if it's not one.
|
||||
"config" OpenSSH's config read (a path; "" its own ~/.ssh/config)
|
||||
"knownhosts" the host's key looked up there (a path; "" OpenSSH's)
|
||||
"hostkeys" the host key algorithms, in order (a list with commas)
|
||||
"timeout" seconds to connect in
|
||||
"compression" "yes" or "no" */
|
||||
int dmc_ssh_option(dmc_ssh *s, const char *name, const char *value);
|
||||
/* the next event: 1 (in *ev), 0 when timeout_ms passed with none, -1
|
||||
when the connection is over and its DMC_SSH_EV_CLOSED was handed back */
|
||||
int dmc_ssh_poll(dmc_ssh *s, int timeout_ms, dmc_ssh_event *ev);
|
||||
/* the connection closed by the user: a DMC_SSH_EV_CLOSED with NULL comes */
|
||||
void dmc_ssh_disconnect(dmc_ssh *s);
|
||||
|
||||
/* the server's key: trusted (ok) or not; remember: added to known_hosts */
|
||||
void dmc_ssh_trust(dmc_ssh *s, int ok, int remember);
|
||||
/* a login tried (an answer to DMC_SSH_EV_AUTH) */
|
||||
void dmc_ssh_auth_password(dmc_ssh *s, const char *password);
|
||||
/* by a private key's text (OpenSSH's, PEM): 0, or -1 when it can't be
|
||||
read with that passphrase (nothing is tried: answer again) */
|
||||
int dmc_ssh_auth_key(dmc_ssh *s, const char *key, const char *passphrase);
|
||||
/* by the system's agent (SSH_AUTH_SOCK) */
|
||||
void dmc_ssh_auth_agent(dmc_ssh *s);
|
||||
/* as OpenSSH's ssh does: the agent, then ~/.ssh's keys with no passphrase */
|
||||
void dmc_ssh_auth_auto(dmc_ssh *s);
|
||||
/* by the server's questions (keyboard-interactive) */
|
||||
void dmc_ssh_auth_interactive(dmc_ssh *s);
|
||||
/* no more tries: the connection closes, "not logged in" */
|
||||
void dmc_ssh_auth_cancel(dmc_ssh *s);
|
||||
/* a DMC_SSH_EV_PROMPTS round: its instruction, and question i (*echo:
|
||||
whether the answer may be shown) */
|
||||
const char *dmc_ssh_instruction(dmc_ssh *s);
|
||||
const char *dmc_ssh_prompt(dmc_ssh *s, int i, int *echo);
|
||||
void dmc_ssh_answer(dmc_ssh *s, int i, const char *answer);
|
||||
void dmc_ssh_answered(dmc_ssh *s);
|
||||
|
||||
/* channels, once ready: each a number (1 and up), or -1; a
|
||||
DMC_SSH_EV_OPEN tells whether it opened */
|
||||
/* a shell on a pty of term in the given size; agent: ssh -A asked */
|
||||
int dmc_ssh_shell(dmc_ssh *s, const char *term, int cols, int rows, int agent);
|
||||
/* a command run, with no pty */
|
||||
int dmc_ssh_exec(dmc_ssh *s, const char *command);
|
||||
/* a TCP connection made from the server to host:port (ssh -L, -D), for
|
||||
a connection that came from from_host:from_port */
|
||||
int dmc_ssh_direct(dmc_ssh *s, const char *host, int port,
|
||||
const char *from_host, int from_port);
|
||||
/* the server asked to listen on address:port (ssh -R; NULL: its
|
||||
default, 0: a port it picks): a request's number, answered by a
|
||||
DMC_SSH_EV_LISTEN; its connections come as DMC_SSH_EV_INCOMING */
|
||||
int dmc_ssh_listen(dmc_ssh *s, const char *address, int port);
|
||||
/* that listen stopped */
|
||||
void dmc_ssh_unlisten(dmc_ssh *s, const char *address, int port);
|
||||
/* data to a channel (kept until the server can take it): 0, or -1 if
|
||||
the channel isn't open */
|
||||
int dmc_ssh_write(dmc_ssh *s, int channel, const char *data, int len);
|
||||
/* the channel's end of data sent */
|
||||
void dmc_ssh_eof(dmc_ssh *s, int channel);
|
||||
/* the channel closed (a DMC_SSH_EV_CLOSE comes) */
|
||||
void dmc_ssh_close(dmc_ssh *s, int channel);
|
||||
/* a shell's pty resized */
|
||||
void dmc_ssh_resize(dmc_ssh *s, int channel, int cols, int rows);
|
||||
|
||||
/* keys */
|
||||
/* OpenSSH's SHA256 fingerprint of a key's OpenSSH line
|
||||
("SHA256:..."), into buf: 0, or -1 if it isn't a key */
|
||||
int dmc_ssh_fingerprint(const char *keyline, char *buf, int max);
|
||||
/* a new key ("ed25519", "ecdsa" with bits 256, 384 or 521, "rsa" with
|
||||
bits): its private text (OpenSSH's, encrypted with passphrase unless
|
||||
it's NULL or "") and its public line, both to free with
|
||||
dmc_ssh_free_string(): 0, or -1 */
|
||||
int dmc_ssh_keygen(const char *type, int bits, const char *passphrase,
|
||||
char **private_key, char **public_key);
|
||||
/* a private key's public line: 0, or -1 if it can't be read with that
|
||||
passphrase */
|
||||
int dmc_ssh_key_public(const char *key, const char *passphrase,
|
||||
char **public_key);
|
||||
/* a private key written again (OpenSSH's form) with a new passphrase
|
||||
(NULL or "": none): 0, or -1 */
|
||||
int dmc_ssh_key_export(const char *key, const char *passphrase,
|
||||
const char *new_passphrase, char **out);
|
||||
void dmc_ssh_free_string(char *str);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#define closesocket close
|
||||
#endif
|
||||
|
||||
#include "dmodemssh.h"
|
||||
|
||||
static int failures;
|
||||
|
||||
#define CHECK(c) do { if (!(c)) { \
|
||||
fprintf(stderr, "%s:%d: failed: %s\n", __FILE__, __LINE__, #c); \
|
||||
failures++; } } while (0)
|
||||
|
||||
/* a key made, read back, its fingerprint, and with a passphrase */
|
||||
static void test_keys(void)
|
||||
{
|
||||
static const char *types[] = { "ed25519", "ecdsa", "rsa" };
|
||||
static const int bits[] = { 0, 384, 2048 };
|
||||
int i;
|
||||
|
||||
for (i = 0; i < 3; i++) {
|
||||
char *priv = NULL, *pub = NULL, *pub2 = NULL, *enc = NULL;
|
||||
char fp[128];
|
||||
|
||||
CHECK(dmc_ssh_keygen(types[i], bits[i], NULL, &priv, &pub) == 0);
|
||||
if (!priv || !pub)
|
||||
continue;
|
||||
CHECK(strstr(priv, "BEGIN OPENSSH PRIVATE KEY") != NULL);
|
||||
CHECK(dmc_ssh_key_public(priv, NULL, &pub2) == 0);
|
||||
CHECK(pub2 && !strcmp(pub, pub2));
|
||||
CHECK(dmc_ssh_fingerprint(pub, fp, sizeof fp) == 0);
|
||||
CHECK(!strncmp(fp, "SHA256:", 7) && strlen(fp) == 50);
|
||||
CHECK(dmc_ssh_key_export(priv, NULL, "sesame", &enc) == 0);
|
||||
dmc_ssh_free_string(pub2);
|
||||
pub2 = NULL;
|
||||
CHECK(enc && dmc_ssh_key_public(enc, "wrong", &pub2) < 0);
|
||||
CHECK(enc && dmc_ssh_key_public(enc, "sesame", &pub2) == 0);
|
||||
CHECK(pub2 && !strcmp(pub, pub2));
|
||||
dmc_ssh_free_string(priv);
|
||||
dmc_ssh_free_string(pub);
|
||||
dmc_ssh_free_string(pub2);
|
||||
dmc_ssh_free_string(enc);
|
||||
}
|
||||
{
|
||||
char fp[128];
|
||||
CHECK(dmc_ssh_fingerprint("ssh-ed25519 notbase64!", fp, sizeof fp) < 0);
|
||||
}
|
||||
}
|
||||
|
||||
static const char *host, *user, *password;
|
||||
static int port;
|
||||
|
||||
/* the next event (10 s at most): its type, or 0 */
|
||||
static int next(dmc_ssh *s, dmc_ssh_event *ev)
|
||||
{
|
||||
int r = dmc_ssh_poll(s, 10000, ev);
|
||||
|
||||
if (r <= 0) {
|
||||
fprintf(stderr, "no event (%d)\n", r);
|
||||
return 0;
|
||||
}
|
||||
return ev->type;
|
||||
}
|
||||
|
||||
/* a connection logged in by password (a wrong one first): or NULL */
|
||||
static dmc_ssh *logged_in(void)
|
||||
{
|
||||
dmc_ssh *s = dmc_ssh_new(host, port, user);
|
||||
dmc_ssh_event ev;
|
||||
|
||||
CHECK(next(s, &ev) == DMC_SSH_EV_HOSTKEY);
|
||||
CHECK(!strncmp(ev.data, "ssh-", 4) || !strncmp(ev.data, "ecdsa-", 6));
|
||||
CHECK(ev.value == DMC_SSH_HOST_UNCHECKED);
|
||||
dmc_ssh_trust(s, 1, 0);
|
||||
CHECK(next(s, &ev) == DMC_SSH_EV_AUTH);
|
||||
CHECK(ev.value & DMC_SSH_AUTH_PASSWORD);
|
||||
CHECK(!strcmp(ev.data, ""));
|
||||
dmc_ssh_auth_password(s, "not it");
|
||||
CHECK(next(s, &ev) == DMC_SSH_EV_AUTH);
|
||||
CHECK(!strcmp(ev.data, "The password was not accepted"));
|
||||
dmc_ssh_auth_password(s, password);
|
||||
if (next(s, &ev) != DMC_SSH_EV_READY) {
|
||||
CHECK(!"logged in");
|
||||
dmc_ssh_free(s);
|
||||
return NULL;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/* a channel's output read until it closes: into out; its exit status */
|
||||
static int drain(dmc_ssh *s, int ch, char *out, int max)
|
||||
{
|
||||
dmc_ssh_event ev;
|
||||
int len = 0, status = -1000;
|
||||
|
||||
for (;;) {
|
||||
int t = next(s, &ev);
|
||||
|
||||
if (!t || t == DMC_SSH_EV_CLOSED)
|
||||
break;
|
||||
if (ev.channel != ch)
|
||||
continue;
|
||||
if (t == DMC_SSH_EV_DATA && len + ev.len < max) {
|
||||
memcpy(out + len, ev.data, (size_t)ev.len);
|
||||
len += ev.len;
|
||||
} else if (t == DMC_SSH_EV_EXIT) {
|
||||
status = ev.value;
|
||||
} else if (t == DMC_SSH_EV_CLOSE) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out[len] = 0;
|
||||
return status;
|
||||
}
|
||||
|
||||
/* a shell on a pty: its size, a command typed, its exit */
|
||||
static void test_shell(dmc_ssh *s)
|
||||
{
|
||||
dmc_ssh_event ev;
|
||||
char out[8192];
|
||||
int ch = dmc_ssh_shell(s, "vt100", 100, 30, 0);
|
||||
static const char typed[] = "stty size; echo $TERM; exit 3\n";
|
||||
|
||||
CHECK(ch > 0);
|
||||
CHECK(next(s, &ev) == DMC_SSH_EV_OPEN && ev.channel == ch && ev.value == 1);
|
||||
CHECK(dmc_ssh_write(s, ch, typed, (int)strlen(typed)) == 0);
|
||||
CHECK(drain(s, ch, out, sizeof out) == 3);
|
||||
CHECK(strstr(out, "30 100") != NULL);
|
||||
CHECK(strstr(out, "vt100") != NULL);
|
||||
CHECK(dmc_ssh_write(s, ch, "x", 1) < 0);
|
||||
}
|
||||
|
||||
/* a command: its output, stdin, and exit status */
|
||||
static void test_exec(dmc_ssh *s)
|
||||
{
|
||||
dmc_ssh_event ev;
|
||||
char out[8192];
|
||||
int ch = dmc_ssh_exec(s, "tr a-z A-Z; exit 7");
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user