From ab601f71a6513d32f27d7f77ee39f663b6b63f31 Mon Sep 17 00:00:00 2001 From: Kristian Larsson Date: Thu, 29 Oct 2026 11:45:30 +0100 Subject: [PATCH] Report SSH connect failures as SSH errors Client.on_connect reported every failure as a string, and SshPipe made each one an OSError, so a key exchange mismatch looked like a socket failure. on_connect now gets an exception: an OSError only when the connect failed before the server's SSH banner, like a refused TCP connect, and otherwise an SshError. Its subclasses are the failures that need a change on one side: KeyExchangeError when client and server share no algorithm, HostKeyError when the host key is not trusted, and AuthenticationError when the server refuses the credentials. SshPipe passes the error on, and reports a refused channel as an SshError. The end of a connection stays an OSError, as on TCP. on_connect's err changes type from ?str to ?Exception. --- README.md | 9 ++- src/bench_echo.act | 4 +- src/example_client.act | 2 +- src/interop_client.act | 2 +- src/lib.act | 45 ++++++++++++-- src/lib.ext.c | 127 ++++++++++++++++++++++++++------------ src/pipe.act | 17 ++++-- src/soak.act | 4 +- src/test_interop.act | 8 ++- src/test_ssh.act | 134 +++++++++++++++++++++++++++++++++++------ src/test_ssh_pipe.act | 11 +++- 11 files changed, 282 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index e827ce8..42043e8 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ actor main(env): # Verify info.fingerprint against a known value in production. c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: print("connect failed:", err) env.exit(1) @@ -231,7 +231,12 @@ the server generates an ephemeral in-memory key using `host_key_type` and and/or `private_keys: list[PrivateKey]`. Tunables: `port`, in-memory `known_hosts`, `transport`, `connect_timeout`, `auth_timeout`, `keepalive_interval`, `keepalive_enabled`, `close_timeout`, - `max_write_buffer`. + `max_write_buffer`. A failed connect reports `on_connect(client, err)` with + an `OSError` when it failed before the server's SSH banner, like a refused + TCP connect, and otherwise an `SshError`: `KeyExchangeError` when client + and server share no algorithm, `HostKeyError` when the host key is not + trusted, `AuthenticationError` when the server refuses the credentials. + `SshPipe` reports the same errors. - **`Channel(client, on_open, on_stdout, on_stderr, on_exit, on_close)`** — `request_exec(cmd)`, `request_shell(...)`, `request_subsystem(name)`, `write(data)`, `send_eof()`, `close()`. `?bytes` callbacks deliver `None` diff --git a/src/bench_echo.act b/src/bench_echo.act index 425fafd..41a59b4 100644 --- a/src/bench_echo.act +++ b/src/bench_echo.act @@ -69,9 +69,9 @@ actor main(env): def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: - fail("connect: " + err) + fail("connect: " + str(err)) return t_connect = time.monotonic() ssh.Channel(c, ch_open, ch_out, ch_err, ch_exit, ch_close) diff --git a/src/example_client.act b/src/example_client.act index a03d1c1..7a2d8fa 100644 --- a/src/example_client.act +++ b/src/example_client.act @@ -54,7 +54,7 @@ actor main(env): print("host key [" + state + "]", info.key_type, info.fingerprint) c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: print("connect error:", err) env.exit(1) diff --git a/src/interop_client.act b/src/interop_client.act index 9c5eecd..b27a5f9 100644 --- a/src/interop_client.act +++ b/src/interop_client.act @@ -40,7 +40,7 @@ actor main(env): print("HOSTKEY", state, info.key_type, info.fingerprint) c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: print("CONNECT-ERROR", err) env.exit(1) diff --git a/src/lib.act b/src/lib.act index 6f45436..04f2192 100644 --- a/src/lib.act +++ b/src/lib.act @@ -41,7 +41,10 @@ Authentication (client): - If neither is given, the connection fails. Callback ordering and semantics: - - All operations are async actor actions; callbacks receive errors as ?str. + - All operations are async actor actions. Client.on_connect receives an + error as ?Exception: SshError or one of its subclasses, or OSError for a + failure before the server's SSH banner. Other callbacks receive errors + as ?str. - ?bytes data callbacks use None to signal EOF (end of that stream). - On channel teardown the delivery order is: on_exit (if the remote sent an exit status), then on_stdout(None) / on_stderr(None) for streams that have @@ -69,6 +72,36 @@ Notes: import net +class SshError(Exception): + """An SSH connection failed after the server's SSH banner arrived. + + Client.on_connect reports a failure before the banner, like a refused + TCP connect, as an OSError. The subclasses are the failures that need a + change on one side to go away. + """ + pass + + +class KeyExchangeError(SshError): + """The key exchange failed, as when client and server share no key + exchange, host key, cipher or MAC algorithm. Client's transport sets + what the client offers.""" + pass + + +class HostKeyError(SshError): + """The client did not trust the server's host key: the key does not match + known_hosts, on_hostkey rejected it or did not answer in time, or there + is no on_hostkey to ask.""" + pass + + +class AuthenticationError(SshError): + """The server refused every credential the client offered, or the client + had none to offer.""" + pass + + class Algorithm: """An algorithm supported by the bundled libssh build.""" _name: str @@ -587,7 +620,7 @@ class AuthRequest(): actor Client(cap: net.TCPConnectCap, host: str, username: str, - on_connect: action(Client, ?str) -> None, + on_connect: action(Client, ?Exception) -> None, on_close: action(Client, str) -> None, on_hostkey: ?action(Client, str, HostKeyInfo) -> None=None, password: ?str=None, @@ -605,7 +638,11 @@ actor Client(cap: net.TCPConnectCap, """SSH Client Connects to host:port as username. on_connect(err) fires exactly once: - err is None on success, otherwise a description of the failure. + err is None on success. A failure before the server's SSH banner, like a + refused TCP connect, is an OSError. After the banner it is a + KeyExchangeError while client and server agree on algorithms and keys, a + HostKeyError when the host key is not trusted, an AuthenticationError + when the server refuses the credentials, and otherwise an SshError. on_close(reason) fires exactly once after a successful connect when the session ends. on_hostkey is invoked for host key verification when the key is not already trusted via the in-memory known_hosts data; respond @@ -648,7 +685,7 @@ actor Client(cap: net.TCPConnectCap, var _keepalive_enabled: bool = keepalive_enabled var _close_timeout: float = close_timeout var _max_write_buffer: int = max_write_buffer - var _on_connect: action(Client, ?str) -> None = on_connect + var _on_connect: action(Client, ?Exception) -> None = on_connect var _on_close: action(Client, str) -> None = on_close var _on_hostkey: ?action(Client, str, HostKeyInfo) -> None = on_hostkey diff --git a/src/lib.ext.c b/src/lib.ext.c index d32daea..518790b 100644 --- a/src/lib.ext.c +++ b/src/lib.ext.c @@ -140,6 +140,15 @@ typedef enum { CLIENT_STATE_CLOSED, } client_state_t; +// The exception on_connect reports for a client failure. +typedef enum { + CLIENT_ERR_OS = 0, // OSError: before the server's SSH banner + CLIENT_ERR_SSH, // SshError + CLIENT_ERR_KEX, // KeyExchangeError + CLIENT_ERR_HOSTKEY, // HostKeyError + CLIENT_ERR_AUTH, // AuthenticationError +} client_err_t; + typedef enum { CHAN_STATE_INIT = 0, CHAN_STATE_OPENING, @@ -958,7 +967,36 @@ static int session_channel_limit_reached(ssh_server_session_ctx *s) { // --- Client implementation -static void client_notify_connect(ssh_client_ctx *c, const char *err) { +static B_BaseException client_error(client_err_t kind, const char *msg) { + B_str s = to$str((char *)msg); + switch (kind) { + case CLIENT_ERR_SSH: + return (B_BaseException)sshQ_libQ_SshErrorG_new(s); + case CLIENT_ERR_KEX: + return (B_BaseException)sshQ_libQ_KeyExchangeErrorG_new(s); + case CLIENT_ERR_HOSTKEY: + return (B_BaseException)sshQ_libQ_HostKeyErrorG_new(s); + case CLIENT_ERR_AUTH: + return (B_BaseException)sshQ_libQ_AuthenticationErrorG_new(s); + case CLIENT_ERR_OS: + default: + return (B_BaseException)B_OSErrorG_new(s); + } +} + +/* The kind of a failure that libssh reports for the session. Until the + * server's SSH banner arrives the TCP connection is what failed; after it, + * until the host key check, the key exchange. */ +static client_err_t client_session_error(ssh_client_ctx *c) { + if (c->state == CLIENT_STATE_INIT || c->state == CLIENT_STATE_CONNECTING) { + if (c->session == NULL || ssh_get_serverbanner(c->session) == NULL) + return CLIENT_ERR_OS; + return CLIENT_ERR_KEX; + } + return CLIENT_ERR_SSH; +} + +static void client_notify_connect(ssh_client_ctx *c, client_err_t kind, const char *err) { if (c == NULL) return; if (c->connect_notified) @@ -966,7 +1004,7 @@ static void client_notify_connect(ssh_client_ctx *c, const char *err) { sshQ_libQ_Client actor = client_actor_ref(c); if (c->on_connect) { $action2 f = ($action2)c->on_connect; - SSH_DELIVER(f, actor, err ? to$str((char *)err) : B_None); + SSH_DELIVER(f, actor, err ? (B_value)client_error(kind, err) : B_None); } c->connect_notified = 1; if (err == NULL) @@ -986,14 +1024,16 @@ static void client_notify_close(ssh_client_ctx *c, const char *reason) { c->close_notified = 1; } -static void client_fail(ssh_client_ctx *c, const char *msg) { +/* Fail the client. Before it has connected, on_connect gets the exception of + * kind with msg. */ +static void client_fail(ssh_client_ctx *c, client_err_t kind, const char *msg) { if (c == NULL || c->state == CLIENT_STATE_CLOSED || c->state == CLIENT_STATE_ERROR) return; if (ssh_debug_enabled) - ssh_debug_log("client fail: session=%p state=%d msg=%s", (void *)c->session, (int)c->state, msg); + ssh_debug_log("client fail: session=%p state=%d kind=%d msg=%s", (void *)c->session, (int)c->state, (int)kind, msg); c->state = CLIENT_STATE_ERROR; if (!c->connected_ok) - client_notify_connect(c, msg); + client_notify_connect(c, kind, msg); client_close_internal(c, msg, 1); } @@ -1900,7 +1940,7 @@ static int client_check_hostkey(ssh_client_ctx *c) { if (state == SSH_KNOWN_HOSTS_ERROR) { char errmsg[256] = {0}; snprintf(errmsg, sizeof(errmsg), "Unable to parse or check SSH known_hosts data"); - client_fail(c, errmsg); + client_fail(c, CLIENT_ERR_HOSTKEY, errmsg); return -1; } } @@ -1910,7 +1950,7 @@ static int client_check_hostkey(ssh_client_ctx *c) { if (!c->on_hostkey) { char errmsg[256] = {0}; snprintf(errmsg, sizeof(errmsg), "Host key not accepted (%s)", hostkey_state_str(state)); - client_fail(c, errmsg); + client_fail(c, CLIENT_ERR_HOSTKEY, errmsg); return -1; } @@ -1929,10 +1969,14 @@ static int client_check_hostkey(ssh_client_ctx *c) { /* One authentication step. Tries public key auth first (if configured), then * password. Returns SSH_AUTH_SUCCESS, SSH_AUTH_AGAIN (call again on next - * event) or SSH_AUTH_ERROR with errmsg filled in. */ -static int client_auth_step(ssh_client_ctx *c, char *errmsg, size_t errlen) { + * event) or SSH_AUTH_ERROR with errmsg and kind filled in. kind is + * CLIENT_ERR_AUTH when the server refused the credentials or there were none + * to offer. */ +static int client_auth_step(ssh_client_ctx *c, char *errmsg, size_t errlen, client_err_t *kind) { + *kind = CLIENT_ERR_AUTH; sshQ_libQ_Client actor = client_actor_ref(c); if (actor == NULL) { + *kind = CLIENT_ERR_SSH; snprintf(errmsg, errlen, "SSH client actor gone during auth"); return SSH_AUTH_ERROR; } @@ -1971,6 +2015,8 @@ static int client_auth_step(ssh_client_ctx *c, char *errmsg, size_t errlen) { return SSH_AUTH_SUCCESS; if (rc == SSH_AUTH_AGAIN) return SSH_AUTH_AGAIN; + if (rc == SSH_AUTH_ERROR) + *kind = CLIENT_ERR_SSH; snprintf(errmsg, errlen, "SSH auth failed: %s", ssh_get_error(c->session)); return SSH_AUTH_ERROR; } @@ -1984,11 +2030,11 @@ static void connect_timeout_cb(uv_timer_t *timer) { if (c == NULL) return; if (c->state == CLIENT_STATE_HOSTKEY_WAIT) { - client_fail(c, "SSH host key verification timeout"); + client_fail(c, CLIENT_ERR_HOSTKEY, "SSH host key verification timeout"); return; } if (c->state == CLIENT_STATE_CONNECTING || c->state == CLIENT_STATE_HOSTKEY) { - client_fail(c, "SSH connect timeout"); + client_fail(c, client_session_error(c), "SSH connect timeout"); } } @@ -1997,7 +2043,7 @@ static void auth_timeout_cb(uv_timer_t *timer) { if (c == NULL) return; if (c->state == CLIENT_STATE_AUTH) { - client_fail(c, "SSH authentication timeout"); + client_fail(c, CLIENT_ERR_SSH, "SSH authentication timeout"); } } @@ -2015,7 +2061,7 @@ static void keepalive_cb(uv_timer_t *timer) { if (rc != SSH_OK) { char errmsg[256] = {0}; snprintf(errmsg, sizeof(errmsg), "SSH keepalive failed: %s", ssh_get_error(c->session)); - client_fail(c, errmsg); + client_fail(c, CLIENT_ERR_SSH, errmsg); return; } client_update_poll(c); @@ -2088,7 +2134,7 @@ static void client_poll_cb(uv_poll_t *handle, int status, int events) { if (status < 0) { char errmsg[256] = {0}; uv_strerror_r(status, errmsg + strlen(errmsg), sizeof(errmsg) - strlen(errmsg)); - client_fail(c, errmsg); + client_fail(c, CLIENT_ERR_OS, errmsg); return; } int ready = 0; @@ -2110,7 +2156,7 @@ static void client_poll_cb(uv_poll_t *handle, int status, int events) { if (ready && session_event_poll(c->event) != 0) { char errmsg[256] = {0}; session_failure_reason(c->session, errmsg, sizeof(errmsg)); - client_fail(c, errmsg); + client_fail(c, client_session_error(c), errmsg); return; } client_drive(c); @@ -2127,7 +2173,7 @@ static void client_update_poll(ssh_client_ctx *c) { return; int status = ssh_get_status(c->session); if (status & SSH_CLOSED_ERROR) { - client_fail(c, "SSH session closed with error"); + client_fail(c, client_session_error(c), "SSH session closed with error"); return; } if (status & SSH_CLOSED) { @@ -2149,7 +2195,7 @@ static void client_update_poll(ssh_client_ctx *c) { if (uv_rc != 0) { char errmsg[256] = {0}; uv_strerror_r(uv_rc, errmsg + strlen(errmsg), sizeof(errmsg) - strlen(errmsg)); - client_fail(c, errmsg); + client_fail(c, CLIENT_ERR_OS, errmsg); return; } c->poll_events = events; @@ -2170,7 +2216,7 @@ static void client_pump_io(ssh_client_ctx *c) { if (session_event_poll(c->event) != 0) { char errmsg[256] = {0}; session_failure_reason(c->session, errmsg, sizeof(errmsg)); - client_fail(c, errmsg); + client_fail(c, client_session_error(c), errmsg); return; } client_drive(c); @@ -2226,7 +2272,7 @@ static int client_needs_write(ssh_client_ctx *c) { static void client_on_ready(ssh_client_ctx *c) { c->state = CLIENT_STATE_READY; stop_timer(&c->auth_timer, client_timer_close_cb); - client_notify_connect(c, NULL); + client_notify_connect(c, CLIENT_ERR_SSH, NULL); client_start_keepalive(c); client_drive_channels(c); client_update_poll(c); @@ -2249,7 +2295,7 @@ static void client_drive(ssh_client_ctx *c) { int rc = ssh_connect(c->session); if (rc == SSH_OK) { if (fd_set_nonblocking(c->fd) != 0) { - client_fail(c, "Failed to restore SSH session fd nonblocking"); + client_fail(c, CLIENT_ERR_OS, "Failed to restore SSH session fd nonblocking"); return; } c->state = CLIENT_STATE_HOSTKEY; @@ -2267,7 +2313,7 @@ static void client_drive(ssh_client_ctx *c) { } else { char errmsg[256] = {0}; snprintf(errmsg, sizeof(errmsg), "SSH connect failed: %s", ssh_get_error(c->session)); - client_fail(c, errmsg); + client_fail(c, client_session_error(c), errmsg); return; } } @@ -2293,7 +2339,8 @@ static void client_drive(ssh_client_ctx *c) { if (c->state == CLIENT_STATE_AUTH) { char errmsg[512] = {0}; - int rc = client_auth_step(c, errmsg, sizeof(errmsg)); + client_err_t kind; + int rc = client_auth_step(c, errmsg, sizeof(errmsg), &kind); if (rc == SSH_AUTH_SUCCESS) { client_on_ready(c); return; @@ -2307,7 +2354,7 @@ static void client_drive(ssh_client_ctx *c) { client_update_poll(c); return; } else { - client_fail(c, errmsg); + client_fail(c, kind, errmsg); return; } } @@ -2417,7 +2464,7 @@ static void client_close_internal(ssh_client_ctx *c, const char *reason, int for force_close = 1; if (!c->connected_ok && !c->connect_notified) { - client_notify_connect(c, reason ? reason : "closed"); + client_notify_connect(c, CLIENT_ERR_SSH, reason ? reason : "closed"); } if (reason != NULL && c->close_reason == NULL) c->close_reason = acton_strdup(reason); @@ -2505,7 +2552,7 @@ B_NoneType sshQ_libQ__debug(B_str msg) { c->session = ssh_new(); if (c->session == NULL) { - client_fail(c, "Failed to create SSH session"); + client_fail(c, CLIENT_ERR_SSH, "Failed to create SSH session"); return $R_CONT(c$cont, B_None); } @@ -2516,7 +2563,7 @@ B_NoneType sshQ_libQ__debug(B_str msg) { rc = ssh_options_set(c->session, SSH_OPTIONS_PROCESS_CONFIG, &process_config); if (rc != SSH_OK) { - client_fail(c, "Failed to disable SSH config processing"); + client_fail(c, CLIENT_ERR_SSH, "Failed to disable SSH config processing"); return $R_CONT(c$cont, B_None); } @@ -2525,40 +2572,40 @@ B_NoneType sshQ_libQ__debug(B_str msg) { * see the header note. */ rc = ssh_options_set(c->session, SSH_OPTIONS_KNOWNHOSTS, "/dev/null"); if (rc != SSH_OK) { - client_fail(c, "Failed to disable SSH known_hosts files"); + client_fail(c, CLIENT_ERR_SSH, "Failed to disable SSH known_hosts files"); return $R_CONT(c$cont, B_None); } rc = ssh_options_set(c->session, SSH_OPTIONS_GLOBAL_KNOWNHOSTS, "/dev/null"); if (rc != SSH_OK) { - client_fail(c, "Failed to disable SSH global known_hosts files"); + client_fail(c, CLIENT_ERR_SSH, "Failed to disable SSH global known_hosts files"); return $R_CONT(c$cont, B_None); } rc = ssh_options_set(c->session, SSH_OPTIONS_HOST, fromB_str(self->_host)); if (rc != SSH_OK) { - client_fail(c, "Failed to set SSH host"); + client_fail(c, CLIENT_ERR_SSH, "Failed to set SSH host"); return $R_CONT(c$cont, B_None); } rc = ssh_options_set(c->session, SSH_OPTIONS_PORT, &port); if (rc != SSH_OK) { - client_fail(c, "Failed to set SSH port"); + client_fail(c, CLIENT_ERR_SSH, "Failed to set SSH port"); return $R_CONT(c$cont, B_None); } rc = ssh_options_set(c->session, SSH_OPTIONS_USER, fromB_str(self->_username)); if (rc != SSH_OK) { - client_fail(c, "Failed to set SSH username"); + client_fail(c, CLIENT_ERR_SSH, "Failed to set SSH username"); return $R_CONT(c$cont, B_None); } rc = ssh_options_set(c->session, SSH_OPTIONS_STRICTHOSTKEYCHECK, &strict); if (rc != SSH_OK) { - client_fail(c, "Failed to set SSH strict host key checking"); + client_fail(c, CLIENT_ERR_SSH, "Failed to set SSH strict host key checking"); return $R_CONT(c$cont, B_None); } char transport_error[256] = {0}; if (apply_client_transport(c->session, self, transport_error, sizeof(transport_error)) != SSH_OK) { - client_fail(c, transport_error); + client_fail(c, CLIENT_ERR_SSH, transport_error); return $R_CONT(c$cont, B_None); } @@ -2575,22 +2622,22 @@ B_NoneType sshQ_libQ__debug(B_str msg) { } else { char errmsg[256] = {0}; snprintf(errmsg, sizeof(errmsg), "SSH connect failed: %s", ssh_get_error(c->session)); - client_fail(c, errmsg); + client_fail(c, client_session_error(c), errmsg); return $R_CONT(c$cont, B_None); } c->fd = ssh_get_fd(c->session); if (c->fd < 0) { - client_fail(c, "Failed to get SSH session fd"); + client_fail(c, CLIENT_ERR_SSH, "Failed to get SSH session fd"); return $R_CONT(c$cont, B_None); } if (c->state != CLIENT_STATE_CONNECTING && fd_set_nonblocking(c->fd) != 0) { - client_fail(c, "Failed to set SSH session fd nonblocking"); + client_fail(c, CLIENT_ERR_OS, "Failed to set SSH session fd nonblocking"); return $R_CONT(c$cont, B_None); } /* Only valid after the ssh_connect() above; see session_event_attach(). */ if (session_event_attach(c->session, &c->event) != 0) { - client_fail(c, "Failed to attach SSH session event"); + client_fail(c, CLIENT_ERR_SSH, "Failed to attach SSH session event"); return $R_CONT(c$cont, B_None); } @@ -2600,7 +2647,7 @@ B_NoneType sshQ_libQ__debug(B_str msg) { if (uv_rc != 0) { char errmsg[256] = {0}; uv_strerror_r(uv_rc, errmsg + strlen(errmsg), sizeof(errmsg) - strlen(errmsg)); - client_fail(c, errmsg); + client_fail(c, CLIENT_ERR_OS, errmsg); return $R_CONT(c$cont, B_None); } c->poll_events = UV_READABLE | UV_WRITABLE; @@ -2608,7 +2655,7 @@ B_NoneType sshQ_libQ__debug(B_str msg) { if (uv_rc != 0) { char errmsg[256] = {0}; uv_strerror_r(uv_rc, errmsg + strlen(errmsg), sizeof(errmsg) - strlen(errmsg)); - client_fail(c, errmsg); + client_fail(c, CLIENT_ERR_OS, errmsg); return $R_CONT(c$cont, B_None); } @@ -2640,7 +2687,7 @@ B_NoneType sshQ_libQ__debug(B_str msg) { char errmsg[256] = {0}; snprintf(errmsg, sizeof(errmsg), "Host key rejected: %s", fromB_str(reason)); - client_fail(c, errmsg); + client_fail(c, CLIENT_ERR_HOSTKEY, errmsg); return $R_CONT(c$cont, B_None); } diff --git a/src/pipe.act b/src/pipe.act index 500bd22..a5f03bf 100644 --- a/src/pipe.act +++ b/src/pipe.act @@ -10,6 +10,9 @@ shell; the channel's stdin/stdout is the pipe. The connection is established lazily when the first read callback is installed (mirroring the other Pipe implementations). The connected signal is read_cb(None, None); data is read_cb(None, data); errors (including channel EOF/close) are read_cb(err, None). +A failed connect gives the error of Client.on_connect, an ssh.SshError or an +OSError, and a refused channel an ssh.SshError. The end of a connection, like +channel EOF or close or the session closing, is an OSError, as on TCP. Server side: SshPipeListener accepts SSH sessions, authenticates them via a caller-supplied check function, and turns each accepted subsystem channel into @@ -161,13 +164,17 @@ actor _SshClientPipeEndpoint(connect_cap: net.TCPConnectCap, _pending_err = None await async _read_cb(err, None) - def _fail(msg: str): + def _fail_with(err: Exception): if _closing or _failed: return _failed = True - _pending_err = OSError(msg) + _pending_err = err _emit_pending() + def _fail(msg: str): + """Fail with an OSError: the connection ended, as a TCP pipe's would.""" + _fail_with(OSError(msg)) + def _on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): if not _is_current_client(c): return @@ -179,11 +186,11 @@ actor _SshClientPipeEndpoint(connect_cap: net.TCPConnectCap, _log.warning("Rejecting SSH host key", {"address": address, "state": state, "fingerprint": info.fingerprint}) c.reject_hostkey("host key not trusted ({state})") - def _on_ssh_connect(c: ssh.Client, err: ?str): + def _on_ssh_connect(c: ssh.Client, err: ?Exception): if _closing or not _is_current_client(c): return if err is not None: - _fail("SSH connection failed: {err}") + _fail_with(err) return # Track the channel from creation, not from on_open: its EOF can arrive # before on_open, and a channel the peer closes while it is still @@ -203,7 +210,7 @@ actor _SshClientPipeEndpoint(connect_cap: net.TCPConnectCap, ch.close() return if err is not None: - _fail("SSH channel open failed: {err}") + _fail_with(ssh.SshError("SSH channel open failed: {err}")) return _channel_open = True sub = subsystem diff --git a/src/soak.act b/src/soak.act index 9c9b7a4..1f97422 100644 --- a/src/soak.act +++ b/src/soak.act @@ -75,9 +75,9 @@ actor main(env): start_cycle() def start_cycle(): - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: - fail("connect: " + err) + fail("connect: " + str(err)) return def on_run_exit(ch: ssh.Channel, code: int, sig: ?str, out: bytes, eb: bytes, error: ?str): if error is None and code == 0 and out == b"ok\n": diff --git a/src/test_interop.act b/src/test_interop.act index ad51c5d..7ae2be4 100644 --- a/src/test_interop.act +++ b/src/test_interop.act @@ -571,12 +571,14 @@ actor SshdTester( def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: - if expect_connect_error: + if expect_connect_error and isinstance(err, ssh.AuthenticationError): finish_ok() + elif expect_connect_error: + finish_error("client connect error: want AuthenticationError, got " + repr(err)) else: - finish_error("client connect error: " + err + + finish_error("client connect error: " + str(err) + " (sshd stderr: " + sshd_err.decode() + ")") return if expect_connect_error: diff --git a/src/test_ssh.act b/src/test_ssh.act index 8a878cb..c7b9141 100644 --- a/src/test_ssh.act +++ b/src/test_ssh.act @@ -219,9 +219,9 @@ actor ExecTester(t: testing.EnvT): def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: - finish_error("client connect error: " + err) + finish_error("client connect error: " + str(err)) return ssh.RunCommand(c, "greet", on_run_exit, timeout=10.0) @@ -372,9 +372,9 @@ actor SubsystemTester(t: testing.EnvT): def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: - finish_error("client connect error: " + err) + finish_error("client connect error: " + str(err)) return ssh.Channel(c, ch_open, ch_out, ch_err, ch_exit, ch_close) @@ -498,10 +498,13 @@ actor AuthRejectTester(t: testing.EnvT): def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is None: finish_error("connect unexpectedly succeeded") return + if not isinstance(err, ssh.AuthenticationError): + finish_error("want AuthenticationError, got " + repr(err)) + return got_auth_error = True if server is not None: server.close() @@ -597,10 +600,13 @@ actor HostkeyRejectTester(t: testing.EnvT): return c.reject_hostkey("untrusted") - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is None: finish_error("connect unexpectedly succeeded") return + if not isinstance(err, ssh.HostKeyError): + finish_error("want HostKeyError, got " + repr(err)) + return got_reject_error = True if server is not None: server.close() @@ -639,6 +645,88 @@ def _test_hostkey_reject(t: testing.EnvT): HostkeyRejectTester(t) +actor KexMismatchTester(t: testing.EnvT): + """A client and server with no key exchange in common must fail to connect + with a KeyExchangeError.""" + var done = False + var server: ?ssh.Server = None + var client: ?ssh.Client = None + + def finish(err: ?Exception): + if done: + return + done = True + if client is not None: + client.close() + if server is not None: + server.close() + if err is not None: + t.error(err) + else: + t.success() + + def on_listen(s: ssh.Server, err: ?str): + if err is not None: + finish(Exception("server listen error: " + err)) + return + port = await async s.bound_port() + client = ssh.Client( + net.TCPConnectCap(net.TCPCap(net.NetCap(t.env.cap))), + "127.0.0.1", + TEST_USER, + on_connect, + on_client_close, + on_hostkey, + password=TEST_PASS, + port=port, + transport=ssh.TransportConfig(key_exchanges=[ssh.kex.ecdh_sha2_nistp256]), + ) + + def on_server_close(s: ssh.Server, reason: str): + pass + + def on_session(sess: ssh.ServerSession): + pass + + def on_auth(sess: ssh.ServerSession, req: ssh.AuthRequest): + sess.accept_auth() + + def on_channel_open(sess: ssh.ServerSession): + sess.reject_channel("no channels") + + def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): + c.accept_hostkey() + + def on_connect(c: ssh.Client, err: ?Exception): + if err is None: + finish(Exception("connect unexpectedly succeeded")) + elif isinstance(err, ssh.KeyExchangeError): + finish(None) + else: + finish(Exception("want KeyExchangeError, got " + repr(err))) + + def on_client_close(c: ssh.Client, reason: str): + pass + + server = ssh.Server( + net.TCPListenCap(net.TCPCap(net.NetCap(t.env.cap))), + "127.0.0.1", + u16(0), + on_listen, + on_server_close, + on_session, + on_auth, + on_channel_open, + transport=ssh.TransportConfig(key_exchanges=[ssh.kex.curve25519_sha256]), + ) + after 10.0: finish(Exception("timeout waiting for key exchange mismatch test")) + + +def _test_kex_mismatch(t: testing.EnvT): + """No key exchange in common must surface as a KeyExchangeError.""" + KexMismatchTester(t) + + actor EchoPayloadTester(t: testing.EnvT): """Client streams a large payload through a server-side echo.""" log = logging.Logger(t.log_handler) @@ -720,9 +808,9 @@ actor EchoPayloadTester(t: testing.EnvT): def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: - finish_error("client connect error: " + err) + finish_error("client connect error: " + str(err)) return ssh.Channel(c, ch_open, ch_out, ch_err, ch_exit, ch_close) @@ -889,9 +977,9 @@ actor ConcurrentChannelsTester(t: testing.EnvT): def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: - finish_error("client connect error: " + err) + finish_error("client connect error: " + str(err)) return for i in range(NUM_CHANNELS): start_run(c, i) @@ -1030,9 +1118,9 @@ actor ServerCloseTester(t: testing.EnvT): def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: - finish_error("client connect error: " + err) + finish_error("client connect error: " + str(err)) return ssh.Channel(c, ch_open, ch_out, ch_err, ch_exit, ch_close) @@ -1139,12 +1227,15 @@ actor ConnectRefusedTester(t: testing.EnvT): def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if done: return if err is None: finish_error("connect unexpectedly succeeded to a closed port") return + if isinstance(err, ssh.SshError) or not isinstance(err, OSError): + finish_error("want OSError, got " + repr(err)) + return done = True t.success() @@ -1281,9 +1372,9 @@ actor PubkeyAuthTester(t: testing.EnvT): def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): finish_error("in-memory known_hosts did not accept the server key: " + state) - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: - finish_error("client connect error: " + err) + finish_error("client connect error: " + str(err)) return ssh.RunCommand(c, "go", on_run_exit, timeout=10.0) @@ -1421,9 +1512,9 @@ actor WriteBufferLimitTester(t: testing.EnvT): def on_hostkey(c: ssh.Client, state: str, info: ssh.HostKeyInfo): c.accept_hostkey() - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if err is not None: - finish_error("client connect error: " + err) + finish_error("client connect error: " + str(err)) return ssh.Channel(c, ch_open, ch_out, ch_err, ch_exit, ch_close) @@ -1545,14 +1636,17 @@ actor HostkeyStallTester(t: testing.EnvT): # Neither accept nor reject: the client stays in CLIENT_STATE_HOSTKEY_WAIT. reached_hostkey = True - def on_connect(c: ssh.Client, err: ?str): + def on_connect(c: ssh.Client, err: ?Exception): if done: return if err is None: finish_error("connect unexpectedly succeeded") return - if not reached_hostkey or err != "SSH host key verification timeout": - finish_error("expected SSH host key verification timeout, got: " + str(err)) + timed_out = False + if err is not None and isinstance(err, ssh.HostKeyError): + timed_out = err.error_message == "SSH host key verification timeout" + if not reached_hostkey or not timed_out: + finish_error("expected HostKeyError for the host key verification timeout, got: " + repr(err)) return done = True if server is not None: diff --git a/src/test_ssh_pipe.act b/src/test_ssh_pipe.act index 1554ff3..3738f87 100644 --- a/src/test_ssh_pipe.act +++ b/src/test_ssh_pipe.act @@ -169,6 +169,8 @@ actor PipeAuthRejectTester(t: testing.EnvT): _teardown() if connected: t.failure(ValueError("connected before auth error")) + elif not isinstance(err, ssh.AuthenticationError): + t.failure(ValueError("expected AuthenticationError, got: {repr(err)}")) else: t.success() elif data is None: @@ -242,6 +244,8 @@ actor PipeConnectTimeoutTester(t: testing.EnvT): t.failure(ValueError("connected to a peer that never sent an SSH banner")) elif str(err).find("SSH connect timeout") < 0: t.failure(ValueError("expected SSH connect timeout, got: {err}")) + elif isinstance(err, ssh.SshError) or not isinstance(err, OSError): + t.failure(ValueError("expected OSError before the SSH banner, got: {repr(err)}")) else: t.success() elif data is None: @@ -323,6 +327,8 @@ actor PipeAuthTimeoutTester(t: testing.EnvT): t.failure(ValueError("connected although authentication was never answered")) elif str(err).find("SSH authentication timeout") < 0: t.failure(ValueError("expected SSH authentication timeout, got: {err}")) + elif isinstance(err, ssh.AuthenticationError) or not isinstance(err, ssh.SshError): + t.failure(ValueError("expected SshError for a timeout, got: {repr(err)}")) else: t.success() elif data is None: @@ -463,7 +469,10 @@ actor PipeStrictHostKeyTester(t: testing.EnvT): if err is not None: done = True _teardown() - t.success() + if isinstance(err, ssh.HostKeyError): + t.success() + else: + t.failure(ValueError("expected HostKeyError, got: {repr(err)}")) elif data is None: done = True _teardown()