1 /* $OpenBSD: clientloop.c,v 1.322 2019/03/29 11:31:40 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The main loop for the interactive session (client side).
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * SSH2 support added by Markus Friedl.
39 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
50 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
51 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
52 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
53 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
54 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
55 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
56 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
57 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
58 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
59 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64 #include <sys/types.h>
65 #include <sys/ioctl.h>
66 #ifdef HAVE_SYS_STAT_H
67 # include <sys/stat.h>
69 #ifdef HAVE_SYS_TIME_H
70 # include <sys/time.h>
72 #include <sys/socket.h>
89 #include "openbsd-compat/sys-queue.h"
101 #include "myproposal.h"
104 #include "readconf.h"
105 #include "clientloop.h"
106 #include "sshconnect.h"
108 #include "atomicio.h"
113 #include "hostfile.h"
116 extern Options options;
118 /* Flag indicating that stdin should be redirected from /dev/null. */
119 extern int stdin_null_flag;
121 /* Flag indicating that no shell has been requested */
122 extern int no_shell_flag;
124 /* Flag indicating that ssh should daemonise after authentication is complete */
125 extern int fork_after_authentication_flag;
128 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
131 * Name of the host we are connecting to. This is the name given on the
132 * command line, or the HostName specified for the user-supplied name in a
133 * configuration file.
138 * Flag to indicate that we have received a window change signal which has
139 * not yet been processed. This will cause a message indicating the new
140 * window size to be sent to the server a little later. This is volatile
141 * because this is updated in a signal handler.
143 static volatile sig_atomic_t received_window_change_signal = 0;
144 static volatile sig_atomic_t received_signal = 0;
146 /* Flag indicating whether the user's terminal is in non-blocking mode. */
147 static int in_non_blocking_mode = 0;
149 /* Time when backgrounded control master using ControlPersist should exit */
150 static time_t control_persist_exit_time = 0;
152 /* Common data for the client loop code. */
153 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
154 static int last_was_cr; /* Last character was a newline. */
155 static int exit_status; /* Used to store the command exit status. */
156 static struct sshbuf *stderr_buffer; /* Used for final exit message. */
157 static int connection_in; /* Connection to server (input). */
158 static int connection_out; /* Connection to server (output). */
159 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
160 static int session_closed; /* In SSH2: login session closed. */
161 static u_int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
163 static void client_init_dispatch(struct ssh *ssh);
164 int session_ident = -1;
166 /* Track escape per proto2 channel */
167 struct escape_filter_ctx {
172 /* Context for channel confirmation replies */
173 struct channel_reply_ctx {
174 const char *request_type;
176 enum confirm_action action;
179 /* Global request success/failure callbacks */
180 /* XXX move to struct ssh? */
181 struct global_confirm {
182 TAILQ_ENTRY(global_confirm) entry;
183 global_confirm_cb *cb;
187 TAILQ_HEAD(global_confirms, global_confirm);
188 static struct global_confirms global_confirms =
189 TAILQ_HEAD_INITIALIZER(global_confirms);
191 void ssh_process_session2_setup(int, int, int, struct sshbuf *);
193 /* Restores stdin to blocking mode. */
196 leave_non_blocking(void)
198 if (in_non_blocking_mode) {
199 unset_nonblock(fileno(stdin));
200 in_non_blocking_mode = 0;
205 * Signal handler for the window change signal (SIGWINCH). This just sets a
206 * flag indicating that the window has changed.
210 window_change_handler(int sig)
212 received_window_change_signal = 1;
216 * Signal handler for signals that cause the program to terminate. These
217 * signals must be trapped to restore terminal modes.
221 signal_handler(int sig)
223 received_signal = sig;
228 * Sets control_persist_exit_time to the absolute time when the
229 * backgrounded control master should exit due to expiry of the
230 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
231 * control master process, or if there is no ControlPersist timeout.
234 set_control_persist_exit_time(struct ssh *ssh)
236 if (muxserver_sock == -1 || !options.control_persist
237 || options.control_persist_timeout == 0) {
238 /* not using a ControlPersist timeout */
239 control_persist_exit_time = 0;
240 } else if (channel_still_open(ssh)) {
241 /* some client connections are still open */
242 if (control_persist_exit_time > 0)
243 debug2("%s: cancel scheduled exit", __func__);
244 control_persist_exit_time = 0;
245 } else if (control_persist_exit_time <= 0) {
246 /* a client connection has recently closed */
247 control_persist_exit_time = monotime() +
248 (time_t)options.control_persist_timeout;
249 debug2("%s: schedule exit in %d seconds", __func__,
250 options.control_persist_timeout);
252 /* else we are already counting down to the timeout */
255 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
257 client_x11_display_valid(const char *display)
264 dlen = strlen(display);
265 for (i = 0; i < dlen; i++) {
266 if (!isalnum((u_char)display[i]) &&
267 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
268 debug("Invalid character '%c' in DISPLAY", display[i]);
275 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
276 #define X11_TIMEOUT_SLACK 60
278 client_x11_get_proto(struct ssh *ssh, const char *display,
279 const char *xauth_path, u_int trusted, u_int timeout,
280 char **_proto, char **_data)
282 char *cmd, line[512], xdisplay[512];
283 char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
284 static char proto[512], data[512];
286 int got_data = 0, generated = 0, do_unlink = 0, r;
288 u_int now, x11_timeout_real;
292 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
294 if (!client_x11_display_valid(display)) {
296 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
300 if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
301 debug("No xauth program.");
305 if (xauth_path != NULL) {
307 * Handle FamilyLocal case where $DISPLAY does
308 * not match an authorization entry. For this we
309 * just try "xauth list unix:displaynum.screennum".
310 * XXX: "localhost" match to determine FamilyLocal
313 if (strncmp(display, "localhost:", 10) == 0) {
314 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
315 display + 10)) < 0 ||
316 (size_t)r >= sizeof(xdisplay)) {
317 error("%s: display name too long", __func__);
324 * Generate an untrusted X11 auth cookie.
326 * The authentication cookie should briefly outlive
327 * ssh's willingness to forward X11 connections to
328 * avoid nasty fail-open behaviour in the X server.
330 mktemp_proto(xauthdir, sizeof(xauthdir));
331 if (mkdtemp(xauthdir) == NULL) {
332 error("%s: mkdtemp: %s",
333 __func__, strerror(errno));
337 if ((r = snprintf(xauthfile, sizeof(xauthfile),
338 "%s/xauthfile", xauthdir)) < 0 ||
339 (size_t)r >= sizeof(xauthfile)) {
340 error("%s: xauthfile path too long", __func__);
347 /* auth doesn't time out */
348 xasprintf(&cmd, "%s -f %s generate %s %s "
350 xauth_path, xauthfile, display,
351 SSH_X11_PROTO, _PATH_DEVNULL);
353 /* Add some slack to requested expiry */
354 if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
355 x11_timeout_real = timeout +
358 /* Don't overflow on long timeouts */
359 x11_timeout_real = UINT_MAX;
361 xasprintf(&cmd, "%s -f %s generate %s %s "
362 "untrusted timeout %u 2>%s",
363 xauth_path, xauthfile, display,
364 SSH_X11_PROTO, x11_timeout_real,
367 debug2("%s: xauth command: %s", __func__, cmd);
369 if (timeout != 0 && x11_refuse_time == 0) {
370 now = monotime() + 1;
371 if (UINT_MAX - timeout < now)
372 x11_refuse_time = UINT_MAX;
374 x11_refuse_time = now + timeout;
375 channel_set_x11_refuse_time(ssh,
378 if (system(cmd) == 0)
384 * When in untrusted mode, we read the cookie only if it was
385 * successfully generated as an untrusted one in the step
388 if (trusted || generated) {
390 "%s %s%s list %s 2>" _PATH_DEVNULL,
392 generated ? "-f " : "" ,
393 generated ? xauthfile : "",
395 debug2("x11_get_proto: %s", cmd);
397 if (f && fgets(line, sizeof(line), f) &&
398 sscanf(line, "%*s %511s %511s", proto, data) == 2)
411 /* Don't fall back to fake X11 data for untrusted forwarding */
412 if (!trusted && !got_data) {
413 error("Warning: untrusted X11 forwarding setup failed: "
414 "xauth key data not generated");
419 * If we didn't get authentication data, just make up some
420 * data. The forwarding code will check the validity of the
421 * response anyway, and substitute this data. The X11
422 * server, however, will ignore this fake data and use
423 * whatever authentication mechanisms it was using otherwise
424 * for the local connection.
430 logit("Warning: No xauth data; "
431 "using fake authentication data for X11 forwarding.");
432 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
433 arc4random_buf(rnd, sizeof(rnd));
434 for (i = 0; i < sizeof(rnd); i++) {
435 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
444 * Checks if the client window has changed, and sends a packet about it to
445 * the server if so. The actual change is detected elsewhere (by a software
446 * interrupt on Unix); this just checks the flag and sends a message if
451 client_check_window_change(struct ssh *ssh)
453 if (!received_window_change_signal)
456 received_window_change_signal = 0;
458 debug2("%s: changed", __func__);
460 channel_send_window_changes(ssh);
464 client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
466 struct global_confirm *gc;
468 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
471 gc->cb(ssh, type, seq, gc->ctx);
472 if (--gc->ref_count <= 0) {
473 TAILQ_REMOVE(&global_confirms, gc, entry);
474 explicit_bzero(gc, sizeof(*gc));
478 ssh_packet_set_alive_timeouts(ssh, 0);
483 server_alive_check(struct ssh *ssh)
487 if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) {
488 logit("Timeout, server %s not responding.", host);
491 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
492 (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 ||
493 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* boolean: want reply */
494 (r = sshpkt_send(ssh)) != 0)
495 fatal("%s: send packet: %s", __func__, ssh_err(r));
496 /* Insert an empty placeholder to maintain ordering */
497 client_register_global_confirm(NULL, NULL);
501 * Waits until the client can do something (some data becomes available on
502 * one of the file descriptors).
505 client_wait_until_can_do_something(struct ssh *ssh,
506 fd_set **readsetp, fd_set **writesetp,
507 int *maxfdp, u_int *nallocp, int rekeying)
509 struct timeval tv, *tvp;
511 time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
514 /* Add any selections by the channel mechanism. */
515 channel_prepare_select(ssh, readsetp, writesetp, maxfdp,
516 nallocp, &minwait_secs);
518 /* channel_prepare_select could have closed the last channel */
519 if (session_closed && !channel_still_open(ssh) &&
520 !ssh_packet_have_data_to_write(ssh)) {
521 /* clear mask since we did not call select() */
522 memset(*readsetp, 0, *nallocp);
523 memset(*writesetp, 0, *nallocp);
527 FD_SET(connection_in, *readsetp);
529 /* Select server connection if have data to write to the server. */
530 if (ssh_packet_have_data_to_write(ssh))
531 FD_SET(connection_out, *writesetp);
534 * Wait for something to happen. This will suspend the process until
535 * some selected descriptor can be read, written, or has some other
536 * event pending, or a timeout expires.
539 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
540 if (options.server_alive_interval > 0) {
541 timeout_secs = options.server_alive_interval;
542 server_alive_time = now + options.server_alive_interval;
544 if (options.rekey_interval > 0 && !rekeying)
545 timeout_secs = MINIMUM(timeout_secs,
546 ssh_packet_get_rekey_timeout(ssh));
547 set_control_persist_exit_time(ssh);
548 if (control_persist_exit_time > 0) {
549 timeout_secs = MINIMUM(timeout_secs,
550 control_persist_exit_time - now);
551 if (timeout_secs < 0)
554 if (minwait_secs != 0)
555 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
556 if (timeout_secs == INT_MAX)
559 tv.tv_sec = timeout_secs;
564 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
567 * We have to clear the select masks, because we return.
568 * We have to return, because the mainloop checks for the flags
569 * set by the signal handlers.
571 memset(*readsetp, 0, *nallocp);
572 memset(*writesetp, 0, *nallocp);
576 /* Note: we might still have data in the buffers. */
577 if ((r = sshbuf_putf(stderr_buffer,
578 "select: %s\r\n", strerror(errno))) != 0)
579 fatal("%s: buffer error: %s", __func__, ssh_err(r));
581 } else if (ret == 0) {
583 * Timeout. Could have been either keepalive or rekeying.
584 * Keepalive we check here, rekeying is checked in clientloop.
586 if (server_alive_time != 0 && server_alive_time <= monotime())
587 server_alive_check(ssh);
593 client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
595 /* Flush stdout and stderr buffers. */
596 if (sshbuf_len(bout) > 0)
597 atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
599 if (sshbuf_len(berr) > 0)
600 atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
603 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
609 /* Send the suspend signal to the program itself. */
610 kill(getpid(), SIGTSTP);
612 /* Reset window sizes in case they have changed */
613 received_window_change_signal = 1;
615 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
619 client_process_net_input(struct ssh *ssh, fd_set *readset)
621 char buf[SSH_IOBUFSZ];
625 * Read input from the server, and add any such data to the buffer of
626 * the packet subsystem.
628 if (FD_ISSET(connection_in, readset)) {
629 /* Read as much as possible. */
630 len = read(connection_in, buf, sizeof(buf));
633 * Received EOF. The remote host has closed the
636 if ((r = sshbuf_putf(stderr_buffer,
637 "Connection to %.300s closed by remote host.\r\n",
639 fatal("%s: buffer error: %s",
640 __func__, ssh_err(r));
645 * There is a kernel bug on Solaris that causes select to
646 * sometimes wake up even though there is no data available.
649 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
654 * An error has encountered. Perhaps there is a
657 if ((r = sshbuf_putf(stderr_buffer,
658 "Read from remote host %.300s: %.100s\r\n",
659 host, strerror(errno))) != 0)
660 fatal("%s: buffer error: %s",
661 __func__, ssh_err(r));
665 ssh_packet_process_incoming(ssh, buf, len);
670 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
672 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
677 * If a TTY was explicitly requested, then a failure to allocate
680 if (cr->action == CONFIRM_TTY &&
681 (options.request_tty == REQUEST_TTY_FORCE ||
682 options.request_tty == REQUEST_TTY_YES))
683 cr->action = CONFIRM_CLOSE;
685 /* XXX suppress on mux _client_ quietmode */
686 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
687 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
689 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
690 debug2("%s request accepted on channel %d",
691 cr->request_type, c->self);
692 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
694 snprintf(errmsg, sizeof(errmsg),
695 "%s request failed\r\n", cr->request_type);
697 snprintf(errmsg, sizeof(errmsg),
698 "%s request failed on channel %d",
699 cr->request_type, c->self);
701 /* If error occurred on primary session channel, then exit */
702 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
705 * If error occurred on mux client, append to
709 if ((r = sshbuf_put(c->extended, errmsg,
710 strlen(errmsg))) != 0)
711 fatal("%s: buffer error %s", __func__,
715 if (cr->action == CONFIRM_TTY) {
717 * If a TTY allocation error occurred, then arrange
718 * for the correct TTY to leave raw mode.
720 if (c->self == session_ident)
723 mux_tty_alloc_failed(ssh, c);
724 } else if (cr->action == CONFIRM_CLOSE) {
725 chan_read_failed(ssh, c);
726 chan_write_failed(ssh, c);
733 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
739 client_expect_confirm(struct ssh *ssh, int id, const char *request,
740 enum confirm_action action)
742 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
744 cr->request_type = request;
747 channel_register_status_confirm(ssh, id, client_status_confirm,
748 client_abandon_status_confirm, cr);
752 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
754 struct global_confirm *gc, *last_gc;
756 /* Coalesce identical callbacks */
757 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
758 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
759 if (++last_gc->ref_count >= INT_MAX)
760 fatal("%s: last_gc->ref_count = %d",
761 __func__, last_gc->ref_count);
765 gc = xcalloc(1, sizeof(*gc));
769 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
773 process_cmdline(struct ssh *ssh)
775 void (*handler)(int);
777 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
780 memset(&fwd, 0, sizeof(fwd));
782 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
783 handler = signal(SIGINT, SIG_IGN);
784 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
787 while (isspace((u_char)*s))
790 s++; /* Skip cmdline '-', if any */
794 if (*s == 'h' || *s == 'H' || *s == '?') {
796 logit(" -L[bind_address:]port:host:hostport "
797 "Request local forward");
798 logit(" -R[bind_address:]port:host:hostport "
799 "Request remote forward");
800 logit(" -D[bind_address:]port "
801 "Request dynamic forward");
802 logit(" -KL[bind_address:]port "
803 "Cancel local forward");
804 logit(" -KR[bind_address:]port "
805 "Cancel remote forward");
806 logit(" -KD[bind_address:]port "
807 "Cancel dynamic forward");
808 if (!options.permit_local_command)
811 "Execute local command");
815 if (*s == '!' && options.permit_local_command) {
832 logit("Invalid command.");
836 while (isspace((u_char)*++s))
839 /* XXX update list of forwards in options */
841 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
842 if (!parse_forward(&fwd, s, 1, 0)) {
843 logit("Bad forwarding close specification.");
847 ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
849 ok = channel_cancel_lport_listener(ssh, &fwd,
850 0, &options.fwd_opts) > 0;
852 ok = channel_cancel_lport_listener(ssh, &fwd,
853 CHANNEL_CANCEL_PORT_STATIC,
854 &options.fwd_opts) > 0;
856 logit("Unknown port forwarding.");
859 logit("Canceled forwarding.");
861 if (!parse_forward(&fwd, s, dynamic, remote)) {
862 logit("Bad forwarding specification.");
865 if (local || dynamic) {
866 if (!channel_setup_local_fwd_listener(ssh, &fwd,
867 &options.fwd_opts)) {
868 logit("Port forwarding failed.");
872 if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
873 logit("Port forwarding failed.");
877 logit("Forwarding port.");
881 signal(SIGINT, handler);
882 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
884 free(fwd.listen_host);
885 free(fwd.listen_path);
886 free(fwd.connect_host);
887 free(fwd.connect_path);
890 /* reasons to suppress output of an escape command in help output */
891 #define SUPPRESS_NEVER 0 /* never suppress, always show */
892 #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
893 #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
894 #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
895 struct escape_help_text {
900 static struct escape_help_text esc_txt[] = {
901 {".", "terminate session", SUPPRESS_MUXMASTER},
902 {".", "terminate connection (and any multiplexed sessions)",
904 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
905 {"C", "open a command line", SUPPRESS_MUXCLIENT},
906 {"R", "request rekey", SUPPRESS_NEVER},
907 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
908 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
909 {"#", "list forwarded connections", SUPPRESS_NEVER},
910 {"&", "background ssh (when waiting for connections to terminate)",
912 {"?", "this message", SUPPRESS_NEVER},
916 print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
919 unsigned int i, suppress_flags;
922 if ((r = sshbuf_putf(b,
923 "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
924 fatal("%s: buffer error: %s", __func__, ssh_err(r));
927 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
928 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
929 (using_stderr ? 0 : SUPPRESS_SYSLOG);
931 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
932 if (esc_txt[i].flags & suppress_flags)
934 if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
935 escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
936 fatal("%s: buffer error: %s", __func__, ssh_err(r));
939 if ((r = sshbuf_putf(b,
940 " %c%c - send the escape character by typing it twice\r\n"
941 "(Note that escapes are only recognized immediately after "
942 "newline.)\r\n", escape_char, escape_char)) != 0)
943 fatal("%s: buffer error: %s", __func__, ssh_err(r));
947 * Process the characters one by one.
950 process_escapes(struct ssh *ssh, Channel *c,
951 struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
959 struct escape_filter_ctx *efc = c->filter_ctx == NULL ?
960 NULL : (struct escape_filter_ctx *)c->filter_ctx;
962 if (c->filter_ctx == NULL)
968 for (i = 0; i < (u_int)len; i++) {
969 /* Get one character at a time. */
972 if (efc->escape_pending) {
973 /* We have previously seen an escape character. */
974 /* Clear the flag now. */
975 efc->escape_pending = 0;
977 /* Process the escaped character. */
980 /* Terminate the connection. */
981 if ((r = sshbuf_putf(berr, "%c.\r\n",
982 efc->escape_char)) != 0)
983 fatal("%s: buffer error: %s",
984 __func__, ssh_err(r));
985 if (c && c->ctl_chan != -1) {
986 chan_read_failed(ssh, c);
987 chan_write_failed(ssh, c);
988 if (c->detach_user) {
992 c->type = SSH_CHANNEL_ABANDONED;
993 sshbuf_reset(c->input);
994 chan_ibuf_empty(ssh, c);
1001 /* XXX support this for mux clients */
1002 if (c && c->ctl_chan != -1) {
1006 snprintf(b, sizeof b, "^Z");
1008 snprintf(b, sizeof b, "%c", ch);
1009 if ((r = sshbuf_putf(berr,
1010 "%c%s escape not available to "
1011 "multiplexed sessions\r\n",
1012 efc->escape_char, b)) != 0)
1013 fatal("%s: buffer error: %s",
1014 __func__, ssh_err(r));
1017 /* Suspend the program. Inform the user */
1018 if ((r = sshbuf_putf(berr,
1019 "%c^Z [suspend ssh]\r\n",
1020 efc->escape_char)) != 0)
1021 fatal("%s: buffer error: %s",
1022 __func__, ssh_err(r));
1024 /* Restore terminal modes and suspend. */
1025 client_suspend_self(bin, bout, berr);
1027 /* We have been continued. */
1031 if ((r = sshbuf_putf(berr,
1032 "%cB\r\n", efc->escape_char)) != 0)
1033 fatal("%s: buffer error: %s",
1034 __func__, ssh_err(r));
1035 channel_request_start(ssh, c->self, "break", 0);
1036 if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
1037 (r = sshpkt_send(ssh)) != 0)
1038 fatal("%s: send packet: %s", __func__,
1043 if (datafellows & SSH_BUG_NOREKEY)
1044 logit("Server does not "
1045 "support re-keying");
1053 if (c && c->ctl_chan != -1)
1055 if (!log_is_on_stderr()) {
1056 if ((r = sshbuf_putf(berr,
1057 "%c%c [Logging to syslog]\r\n",
1058 efc->escape_char, ch)) != 0)
1059 fatal("%s: buffer error: %s",
1060 __func__, ssh_err(r));
1063 if (ch == 'V' && options.log_level >
1065 log_change_level(--options.log_level);
1066 if (ch == 'v' && options.log_level <
1067 SYSLOG_LEVEL_DEBUG3)
1068 log_change_level(++options.log_level);
1069 if ((r = sshbuf_putf(berr,
1070 "%c%c [LogLevel %s]\r\n",
1071 efc->escape_char, ch,
1072 log_level_name(options.log_level))) != 0)
1073 fatal("%s: buffer error: %s",
1074 __func__, ssh_err(r));
1078 if (c && c->ctl_chan != -1)
1081 * Detach the program (continue to serve
1082 * connections, but put in background and no
1083 * more new connections).
1085 /* Restore tty modes. */
1087 options.request_tty == REQUEST_TTY_FORCE);
1089 /* Stop listening for new connections. */
1090 channel_stop_listening(ssh);
1092 if ((r = sshbuf_putf(berr,
1093 "%c& [backgrounded]\n", efc->escape_char))
1095 fatal("%s: buffer error: %s",
1096 __func__, ssh_err(r));
1098 /* Fork into background. */
1101 error("fork: %.100s", strerror(errno));
1104 if (pid != 0) { /* This is the parent. */
1105 /* The parent just exits. */
1108 /* The child continues serving connections. */
1109 /* fake EOF on stdin */
1110 if ((r = sshbuf_put_u8(bin, 4)) != 0)
1111 fatal("%s: buffer error: %s",
1112 __func__, ssh_err(r));
1115 print_escape_help(berr, efc->escape_char,
1116 (c && c->ctl_chan != -1),
1117 log_is_on_stderr());
1121 if ((r = sshbuf_putf(berr, "%c#\r\n",
1122 efc->escape_char)) != 0)
1123 fatal("%s: buffer error: %s",
1124 __func__, ssh_err(r));
1125 s = channel_open_message(ssh);
1126 if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1127 fatal("%s: buffer error: %s",
1128 __func__, ssh_err(r));
1133 if (c && c->ctl_chan != -1)
1135 process_cmdline(ssh);
1139 if (ch != efc->escape_char) {
1140 if ((r = sshbuf_put_u8(bin,
1141 efc->escape_char)) != 0)
1142 fatal("%s: buffer error: %s",
1143 __func__, ssh_err(r));
1146 /* Escaped characters fall through here */
1151 * The previous character was not an escape char.
1152 * Check if this is an escape.
1154 if (last_was_cr && ch == efc->escape_char) {
1156 * It is. Set the flag and continue to
1159 efc->escape_pending = 1;
1165 * Normal character. Record whether it was a newline,
1166 * and append it to the buffer.
1168 last_was_cr = (ch == '\r' || ch == '\n');
1169 if ((r = sshbuf_put_u8(bin, ch)) != 0)
1170 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1177 * Get packets from the connection input buffer, and process them as long as
1178 * there are packets available.
1180 * Any unknown packets received during the actual
1181 * session cause the session to terminate. This is
1182 * intended to make debugging easier since no
1183 * confirmations are sent. Any compatible protocol
1184 * extensions must be negotiated during the
1185 * preparatory phase.
1189 client_process_buffered_input_packets(struct ssh *ssh)
1191 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending);
1194 /* scan buf[] for '~' before sending data to the peer */
1196 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1198 client_new_escape_filter_ctx(int escape_char)
1200 struct escape_filter_ctx *ret;
1202 ret = xcalloc(1, sizeof(*ret));
1203 ret->escape_pending = 0;
1204 ret->escape_char = escape_char;
1208 /* Free the escape filter context on channel free */
1210 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1216 client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1218 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1221 return process_escapes(ssh, c, c->input, c->output, c->extended,
1226 client_channel_closed(struct ssh *ssh, int id, void *arg)
1228 channel_cancel_cleanup(ssh, id);
1230 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1234 * Implements the interactive session with the server. This is called after
1235 * the user has been authenticated, and a command has been started on the
1236 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1237 * used as an escape character for terminating or suspending the session.
1240 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1243 fd_set *readset = NULL, *writeset = NULL;
1244 double start_time, total_time;
1245 int r, max_fd = 0, max_fd2 = 0, len;
1246 u_int64_t ibytes, obytes;
1250 debug("Entering interactive session.");
1252 if (options.control_master &&
1253 !option_clear_or_none(options.control_path)) {
1254 debug("pledge: id");
1255 if (pledge("stdio rpath wpath cpath unix inet dns recvfd proc exec id tty",
1257 fatal("%s pledge(): %s", __func__, strerror(errno));
1259 } else if (options.forward_x11 || options.permit_local_command) {
1260 debug("pledge: exec");
1261 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1263 fatal("%s pledge(): %s", __func__, strerror(errno));
1265 } else if (options.update_hostkeys) {
1266 debug("pledge: filesystem full");
1267 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1269 fatal("%s pledge(): %s", __func__, strerror(errno));
1271 } else if (!option_clear_or_none(options.proxy_command) ||
1272 fork_after_authentication_flag) {
1273 debug("pledge: proc");
1274 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1275 fatal("%s pledge(): %s", __func__, strerror(errno));
1278 debug("pledge: network");
1279 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1280 fatal("%s pledge(): %s", __func__, strerror(errno));
1283 start_time = monotime_double();
1285 /* Initialize variables. */
1288 connection_in = ssh_packet_get_connection_in(ssh);
1289 connection_out = ssh_packet_get_connection_out(ssh);
1290 max_fd = MAXIMUM(connection_in, connection_out);
1294 /* Initialize buffer. */
1295 if ((stderr_buffer = sshbuf_new()) == NULL)
1296 fatal("%s: sshbuf_new failed", __func__);
1298 client_init_dispatch(ssh);
1301 * Set signal handlers, (e.g. to restore non-blocking mode)
1302 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1304 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1305 signal(SIGHUP, signal_handler);
1306 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1307 signal(SIGINT, signal_handler);
1308 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1309 signal(SIGQUIT, signal_handler);
1310 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1311 signal(SIGTERM, signal_handler);
1312 signal(SIGWINCH, window_change_handler);
1315 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1317 session_ident = ssh2_chan_id;
1318 if (session_ident != -1) {
1319 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1320 channel_register_filter(ssh, session_ident,
1321 client_simple_escape_filter, NULL,
1322 client_filter_cleanup,
1323 client_new_escape_filter_ctx(
1326 channel_register_cleanup(ssh, session_ident,
1327 client_channel_closed, 0);
1330 /* Main loop of the client for the interactive session mode. */
1331 while (!quit_pending) {
1333 /* Process buffered packets sent by the server. */
1334 client_process_buffered_input_packets(ssh);
1336 if (session_closed && !channel_still_open(ssh))
1339 if (ssh_packet_is_rekeying(ssh)) {
1340 debug("rekeying in progress");
1341 } else if (need_rekeying) {
1342 /* manual rekey request */
1343 debug("need rekeying");
1344 if ((r = kex_start_rekex(ssh)) != 0)
1345 fatal("%s: kex_start_rekex: %s", __func__,
1350 * Make packets from buffered channel data, and
1351 * enqueue them for sending to the server.
1353 if (ssh_packet_not_very_much_data_to_write(ssh))
1354 channel_output_poll(ssh);
1357 * Check if the window size has changed, and buffer a
1358 * message about it to the server if so.
1360 client_check_window_change(ssh);
1366 * Wait until we have something to do (something becomes
1367 * available on one of the descriptors).
1370 client_wait_until_can_do_something(ssh, &readset, &writeset,
1371 &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh));
1376 /* Do channel operations unless rekeying in progress. */
1377 if (!ssh_packet_is_rekeying(ssh))
1378 channel_after_select(ssh, readset, writeset);
1380 /* Buffer input from the connection. */
1381 client_process_net_input(ssh, readset);
1387 * Send as much buffered packet data as possible to the
1390 if (FD_ISSET(connection_out, writeset))
1391 ssh_packet_write_poll(ssh);
1394 * If we are a backgrounded control master, and the
1395 * timeout has expired without any active client
1396 * connections, then quit.
1398 if (control_persist_exit_time > 0) {
1399 if (monotime() >= control_persist_exit_time) {
1400 debug("ControlPersist timeout expired");
1408 /* Terminate the session. */
1410 /* Stop watching for window change. */
1411 signal(SIGWINCH, SIG_DFL);
1413 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
1414 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 ||
1415 (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 ||
1416 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* language tag */
1417 (r = sshpkt_send(ssh)) != 0 ||
1418 (r = ssh_packet_write_wait(ssh)) != 0)
1419 fatal("%s: send disconnect: %s", __func__, ssh_err(r));
1421 channel_free_all(ssh);
1424 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1426 /* restore blocking io */
1427 if (!isatty(fileno(stdin)))
1428 unset_nonblock(fileno(stdin));
1429 if (!isatty(fileno(stdout)))
1430 unset_nonblock(fileno(stdout));
1431 if (!isatty(fileno(stderr)))
1432 unset_nonblock(fileno(stderr));
1435 * If there was no shell or command requested, there will be no remote
1436 * exit status to be returned. In that case, clear error code if the
1437 * connection was deliberately terminated at this end.
1439 if (no_shell_flag && received_signal == SIGTERM) {
1440 received_signal = 0;
1444 if (received_signal) {
1445 verbose("Killed by signal %d.", (int) received_signal);
1450 * In interactive mode (with pseudo tty) display a message indicating
1451 * that the connection has been closed.
1453 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1454 if ((r = sshbuf_putf(stderr_buffer,
1455 "Connection to %.64s closed.\r\n", host)) != 0)
1456 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1459 /* Output any buffered data for stderr. */
1460 if (sshbuf_len(stderr_buffer) > 0) {
1461 len = atomicio(vwrite, fileno(stderr),
1462 (u_char *)sshbuf_ptr(stderr_buffer),
1463 sshbuf_len(stderr_buffer));
1464 if (len < 0 || (u_int)len != sshbuf_len(stderr_buffer))
1465 error("Write failed flushing stderr buffer.");
1466 else if ((r = sshbuf_consume(stderr_buffer, len)) != 0)
1467 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1470 /* Clear and free any buffers. */
1471 explicit_bzero(buf, sizeof(buf));
1472 sshbuf_free(stderr_buffer);
1474 /* Report bytes transferred, and transfer rates. */
1475 total_time = monotime_double() - start_time;
1476 ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1477 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1478 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1480 verbose("Bytes per second: sent %.1f, received %.1f",
1481 obytes / total_time, ibytes / total_time);
1482 /* Return the exit status of the program. */
1483 debug("Exit status %d", exit_status);
1490 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1491 int rchan, u_int rwindow, u_int rmaxpack)
1494 struct sshbuf *b = NULL;
1495 char *listen_address, *originator_address;
1496 u_int listen_port, originator_port;
1499 /* Get rest of the packet */
1500 if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 ||
1501 (r = sshpkt_get_u32(ssh, &listen_port)) != 0 ||
1502 (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 ||
1503 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1504 (r = sshpkt_get_end(ssh)) != 0)
1505 fatal("%s: parse packet: %s", __func__, ssh_err(r));
1507 debug("%s: listen %s port %d, originator %s port %d", __func__,
1508 listen_address, listen_port, originator_address, originator_port);
1510 if (listen_port > 0xffff)
1511 error("%s: invalid listen port", __func__);
1512 else if (originator_port > 0xffff)
1513 error("%s: invalid originator port", __func__);
1515 c = channel_connect_by_listen_address(ssh,
1516 listen_address, listen_port, "forwarded-tcpip",
1517 originator_address);
1520 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1521 if ((b = sshbuf_new()) == NULL) {
1522 error("%s: alloc reply", __func__);
1525 /* reconstruct and send to muxclient */
1526 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1527 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1528 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1529 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1530 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1531 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1532 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1533 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1534 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1535 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1536 (r = sshbuf_put_stringb(c->output, b)) != 0) {
1537 error("%s: compose for muxclient %s", __func__,
1545 free(originator_address);
1546 free(listen_address);
1551 client_request_forwarded_streamlocal(struct ssh *ssh,
1552 const char *request_type, int rchan)
1558 /* Get the remote path. */
1559 if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 ||
1560 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* reserved */
1561 (r = sshpkt_get_end(ssh)) != 0)
1562 fatal("%s: parse packet: %s", __func__, ssh_err(r));
1564 debug("%s: request: %s", __func__, listen_path);
1566 c = channel_connect_by_listen_path(ssh, listen_path,
1567 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1573 client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1577 u_int originator_port;
1580 if (!options.forward_x11) {
1581 error("Warning: ssh server tried X11 forwarding.");
1582 error("Warning: this is probably a break-in attempt by a "
1583 "malicious server.");
1586 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1587 verbose("Rejected X11 connection after ForwardX11Timeout "
1591 if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
1592 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1593 (r = sshpkt_get_end(ssh)) != 0)
1594 fatal("%s: parse packet: %s", __func__, ssh_err(r));
1595 /* XXX check permission */
1596 /* XXX range check originator port? */
1597 debug("client_request_x11: request from %s %u", originator,
1600 sock = x11_connect_display(ssh);
1603 c = channel_new(ssh, "x11",
1604 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1605 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1611 client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1616 if (!options.forward_agent) {
1617 error("Warning: ssh server tried agent forwarding.");
1618 error("Warning: this is probably a break-in attempt by a "
1619 "malicious server.");
1622 if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1623 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1624 debug("%s: ssh_get_authentication_socket: %s",
1625 __func__, ssh_err(r));
1628 c = channel_new(ssh, "authentication agent connection",
1629 SSH_CHANNEL_OPEN, sock, sock, -1,
1630 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1631 "authentication agent connection", 1);
1637 client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1638 int local_tun, int remote_tun)
1642 char *ifname = NULL;
1644 if (tun_mode == SSH_TUNMODE_NO)
1647 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1649 /* Open local tunnel device */
1650 if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1651 error("Tunnel device open failed.");
1654 debug("Tunnel forwarding using interface %s", ifname);
1656 c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1657 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1660 #if defined(SSH_TUN_FILTER)
1661 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1662 channel_register_filter(ssh, c->self, sys_tun_infilter,
1663 sys_tun_outfilter, NULL, NULL);
1666 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1667 (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 ||
1668 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1669 (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 ||
1670 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1671 (r = sshpkt_put_u32(ssh, tun_mode)) != 0 ||
1672 (r = sshpkt_put_u32(ssh, remote_tun)) != 0 ||
1673 (r = sshpkt_send(ssh)) != 0)
1674 sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1679 /* XXXX move to generic input handler */
1681 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1688 u_int rmaxpack, rwindow;
1690 if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 ||
1691 (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
1692 (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
1693 (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
1696 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1697 ctype, rchan, rwindow, rmaxpack);
1699 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1700 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1702 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1703 c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1704 } else if (strcmp(ctype, "x11") == 0) {
1705 c = client_request_x11(ssh, ctype, rchan);
1706 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1707 c = client_request_agent(ssh, ctype, rchan);
1709 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1710 debug3("proxied to downstream: %s", ctype);
1711 } else if (c != NULL) {
1712 debug("confirm %s", ctype);
1713 c->remote_id = rchan;
1714 c->have_remote_id = 1;
1715 c->remote_window = rwindow;
1716 c->remote_maxpacket = rmaxpack;
1717 if (c->type != SSH_CHANNEL_CONNECTING) {
1718 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1719 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1720 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1721 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1722 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1723 (r = sshpkt_send(ssh)) != 0)
1724 sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1727 debug("failure %s", ctype);
1728 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1729 (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
1730 (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 ||
1731 (r = sshpkt_put_cstring(ssh, "open failed")) != 0 ||
1732 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1733 (r = sshpkt_send(ssh)) != 0)
1734 sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1743 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1751 if ((r = sshpkt_get_u32(ssh, &id)) != 0)
1754 c = channel_lookup(ssh, id);
1755 if (channel_proxy_upstream(c, type, seq, ssh))
1757 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
1758 (r = sshpkt_get_u8(ssh, &reply)) != 0)
1761 debug("client_input_channel_req: channel %u rtype %s reply %d",
1765 error("client_input_channel_req: channel %d: "
1766 "unknown channel", id);
1767 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1768 if ((r = sshpkt_get_end(ssh)) != 0)
1770 chan_rcvd_eow(ssh, c);
1771 } else if (strcmp(rtype, "exit-status") == 0) {
1772 if ((r = sshpkt_get_u32(ssh, &exitval)) != 0)
1774 if (c->ctl_chan != -1) {
1775 mux_exit_message(ssh, c, exitval);
1777 } else if ((int)id == session_ident) {
1778 /* Record exit value of local session */
1780 exit_status = exitval;
1782 /* Probably for a mux channel that has already closed */
1783 debug("%s: no sink for exit-status on channel %d",
1786 if ((r = sshpkt_get_end(ssh)) != 0)
1789 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1790 if (!c->have_remote_id)
1791 fatal("%s: channel %d: no remote_id",
1793 if ((r = sshpkt_start(ssh, success ?
1794 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
1795 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1796 (r = sshpkt_send(ssh)) != 0)
1797 sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1805 struct hostkeys_update_ctx {
1806 /* The hostname and (optionally) IP address string for the server */
1807 char *host_str, *ip_str;
1810 * Keys received from the server and a flag for each indicating
1811 * whether they already exist in known_hosts.
1812 * keys_seen is filled in by hostkeys_find() and later (for new
1813 * keys) by client_global_hostkeys_private_confirm().
1815 struct sshkey **keys;
1820 * Keys that are in known_hosts, but were not present in the update
1821 * from the server (i.e. scheduled to be deleted).
1822 * Filled in by hostkeys_find().
1824 struct sshkey **old_keys;
1829 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
1835 for (i = 0; i < ctx->nkeys; i++)
1836 sshkey_free(ctx->keys[i]);
1838 free(ctx->keys_seen);
1839 for (i = 0; i < ctx->nold; i++)
1840 sshkey_free(ctx->old_keys[i]);
1841 free(ctx->old_keys);
1842 free(ctx->host_str);
1848 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
1850 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1852 struct sshkey **tmp;
1854 if (l->status != HKF_STATUS_MATCHED || l->key == NULL)
1857 /* Mark off keys we've already seen for this host */
1858 for (i = 0; i < ctx->nkeys; i++) {
1859 if (sshkey_equal(l->key, ctx->keys[i])) {
1860 debug3("%s: found %s key at %s:%ld", __func__,
1861 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
1862 ctx->keys_seen[i] = 1;
1866 /* This line contained a key that not offered by the server */
1867 debug3("%s: deprecated %s key at %s:%ld", __func__,
1868 sshkey_ssh_name(l->key), l->path, l->linenum);
1869 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1870 sizeof(*ctx->old_keys))) == NULL)
1871 fatal("%s: recallocarray failed nold = %zu",
1872 __func__, ctx->nold);
1873 ctx->old_keys = tmp;
1874 ctx->old_keys[ctx->nold++] = l->key;
1881 update_known_hosts(struct hostkeys_update_ctx *ctx)
1884 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
1885 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1886 char *fp, *response;
1889 for (i = 0; i < ctx->nkeys; i++) {
1890 if (ctx->keys_seen[i] != 2)
1892 if ((fp = sshkey_fingerprint(ctx->keys[i],
1893 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1894 fatal("%s: sshkey_fingerprint failed", __func__);
1895 do_log2(loglevel, "Learned new hostkey: %s %s",
1896 sshkey_type(ctx->keys[i]), fp);
1899 for (i = 0; i < ctx->nold; i++) {
1900 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
1901 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1902 fatal("%s: sshkey_fingerprint failed", __func__);
1903 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
1904 sshkey_type(ctx->old_keys[i]), fp);
1907 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1908 if (get_saved_tio() != NULL) {
1913 for (i = 0; !quit_pending && i < 3; i++) {
1915 response = read_passphrase("Accept updated hostkeys? "
1916 "(yes/no): ", RP_ECHO);
1917 if (strcasecmp(response, "yes") == 0)
1919 else if (quit_pending || response == NULL ||
1920 strcasecmp(response, "no") == 0) {
1921 options.update_hostkeys = 0;
1924 do_log2(loglevel, "Please enter "
1925 "\"yes\" or \"no\"");
1928 if (quit_pending || i >= 3 || response == NULL)
1929 options.update_hostkeys = 0;
1936 * Now that all the keys are verified, we can go ahead and replace
1937 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
1938 * cancel the operation).
1940 if (options.update_hostkeys != 0 &&
1941 (r = hostfile_replace_entries(options.user_hostfiles[0],
1942 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
1943 options.hash_known_hosts, 0,
1944 options.fingerprint_hash)) != 0)
1945 error("%s: hostfile_replace_entries failed: %s",
1946 __func__, ssh_err(r));
1950 client_global_hostkeys_private_confirm(struct ssh *ssh, int type,
1951 u_int32_t seq, void *_ctx)
1953 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1955 struct sshbuf *signdata;
1956 int r, kexsigtype, use_kexsigtype;
1961 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
1962 if (type != SSH2_MSG_REQUEST_SUCCESS) {
1963 error("Server failed to confirm ownership of "
1964 "private host keys");
1965 hostkeys_update_ctx_free(ctx);
1968 kexsigtype = sshkey_type_plain(
1969 sshkey_type_from_name(ssh->kex->hostkey_alg));
1971 if ((signdata = sshbuf_new()) == NULL)
1972 fatal("%s: sshbuf_new failed", __func__);
1973 /* Don't want to accidentally accept an unbound signature */
1974 if (ssh->kex->session_id_len == 0)
1975 fatal("%s: ssh->kex->session_id_len == 0", __func__);
1977 * Expect a signature for each of the ctx->nnew private keys we
1978 * haven't seen before. They will be in the same order as the
1979 * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
1981 for (ndone = i = 0; i < ctx->nkeys; i++) {
1982 if (ctx->keys_seen[i])
1984 /* Prepare data to be signed: session ID, unique string, key */
1985 sshbuf_reset(signdata);
1986 if ( (r = sshbuf_put_cstring(signdata,
1987 "hostkeys-prove-00@openssh.com")) != 0 ||
1988 (r = sshbuf_put_string(signdata, ssh->kex->session_id,
1989 ssh->kex->session_id_len)) != 0 ||
1990 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
1991 fatal("%s: failed to prepare signature: %s",
1992 __func__, ssh_err(r));
1993 /* Extract and verify signature */
1994 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
1995 error("%s: couldn't parse message: %s",
1996 __func__, ssh_err(r));
2000 * For RSA keys, prefer to use the signature type negotiated
2001 * during KEX to the default (SHA1).
2003 use_kexsigtype = kexsigtype == KEY_RSA &&
2004 sshkey_type_plain(ctx->keys[i]->type) == KEY_RSA;
2005 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
2006 sshbuf_ptr(signdata), sshbuf_len(signdata),
2007 use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0)) != 0) {
2008 error("%s: server gave bad signature for %s key %zu",
2009 __func__, sshkey_type(ctx->keys[i]), i);
2012 /* Key is good. Mark it as 'seen' */
2013 ctx->keys_seen[i] = 2;
2016 if (ndone != ctx->nnew)
2017 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
2018 ndone, ctx->nnew); /* Shouldn't happen */
2019 if ((r = sshpkt_get_end(ssh)) != 0) {
2020 error("%s: protocol error", __func__);
2024 /* Make the edits to known_hosts */
2025 update_known_hosts(ctx);
2027 hostkeys_update_ctx_free(ctx);
2031 * Returns non-zero if the key is accepted by HostkeyAlgorithms.
2032 * Made slightly less trivial by the multiple RSA signature algorithm names.
2035 key_accepted_by_hostkeyalgs(const struct sshkey *key)
2037 const char *ktype = sshkey_ssh_name(key);
2038 const char *hostkeyalgs = options.hostkeyalgorithms != NULL ?
2039 options.hostkeyalgorithms : KEX_DEFAULT_PK_ALG;
2041 if (key == NULL || key->type == KEY_UNSPEC)
2043 if (key->type == KEY_RSA &&
2044 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
2045 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
2047 return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
2051 * Handle hostkeys-00@openssh.com global request to inform the client of all
2052 * the server's hostkeys. The keys are checked against the user's
2053 * HostkeyAlgorithms preference before they are accepted.
2056 client_input_hostkeys(struct ssh *ssh)
2058 const u_char *blob = NULL;
2060 struct sshbuf *buf = NULL;
2061 struct sshkey *key = NULL, **tmp;
2064 static int hostkeys_seen = 0; /* XXX use struct ssh */
2065 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2066 struct hostkeys_update_ctx *ctx = NULL;
2069 fatal("%s: server already sent hostkeys", __func__);
2070 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2072 return 1; /* won't ask in batchmode, so don't even try */
2073 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2076 ctx = xcalloc(1, sizeof(*ctx));
2077 while (ssh_packet_remaining(ssh) > 0) {
2080 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2081 error("%s: couldn't parse message: %s",
2082 __func__, ssh_err(r));
2085 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2086 error("%s: parse key: %s", __func__, ssh_err(r));
2089 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2091 debug3("%s: received %s key %s", __func__,
2092 sshkey_type(key), fp);
2095 if (!key_accepted_by_hostkeyalgs(key)) {
2096 debug3("%s: %s key not permitted by HostkeyAlgorithms",
2097 __func__, sshkey_ssh_name(key));
2101 if (sshkey_is_cert(key)) {
2102 debug3("%s: %s key is a certificate; skipping",
2103 __func__, sshkey_ssh_name(key));
2106 /* Ensure keys are unique */
2107 for (i = 0; i < ctx->nkeys; i++) {
2108 if (sshkey_equal(key, ctx->keys[i])) {
2109 error("%s: received duplicated %s host key",
2110 __func__, sshkey_ssh_name(key));
2114 /* Key is good, record it */
2115 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
2116 sizeof(*ctx->keys))) == NULL)
2117 fatal("%s: recallocarray failed nkeys = %zu",
2118 __func__, ctx->nkeys);
2120 ctx->keys[ctx->nkeys++] = key;
2124 if (ctx->nkeys == 0) {
2125 debug("%s: server sent no hostkeys", __func__);
2129 if ((ctx->keys_seen = calloc(ctx->nkeys,
2130 sizeof(*ctx->keys_seen))) == NULL)
2131 fatal("%s: calloc failed", __func__);
2133 get_hostfile_hostname_ipaddr(host,
2134 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2135 options.port, &ctx->host_str,
2136 options.check_host_ip ? &ctx->ip_str : NULL);
2138 /* Find which keys we already know about. */
2139 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2140 ctx, ctx->host_str, ctx->ip_str,
2141 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2142 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
2146 /* Figure out if we have any new keys to add */
2148 for (i = 0; i < ctx->nkeys; i++) {
2149 if (!ctx->keys_seen[i])
2153 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2154 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2156 if (ctx->nnew == 0 && ctx->nold != 0) {
2157 /* We have some keys to remove. Just do it. */
2158 update_known_hosts(ctx);
2159 } else if (ctx->nnew != 0) {
2161 * We have received hitherto-unseen keys from the server.
2162 * Ask the server to confirm ownership of the private halves.
2164 debug3("%s: asking server to prove ownership for %zu keys",
2165 __func__, ctx->nnew);
2166 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2167 (r = sshpkt_put_cstring(ssh,
2168 "hostkeys-prove-00@openssh.com")) != 0 ||
2169 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2170 fatal("%s: cannot prepare packet: %s",
2171 __func__, ssh_err(r));
2172 if ((buf = sshbuf_new()) == NULL)
2173 fatal("%s: sshbuf_new", __func__);
2174 for (i = 0; i < ctx->nkeys; i++) {
2175 if (ctx->keys_seen[i])
2178 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2179 fatal("%s: sshkey_putb: %s",
2180 __func__, ssh_err(r));
2181 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2182 fatal("%s: sshpkt_put_string: %s",
2183 __func__, ssh_err(r));
2185 if ((r = sshpkt_send(ssh)) != 0)
2186 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2187 client_register_global_confirm(
2188 client_global_hostkeys_private_confirm, ctx);
2189 ctx = NULL; /* will be freed in callback */
2194 hostkeys_update_ctx_free(ctx);
2198 * NB. Return success for all cases. The server doesn't need to know
2199 * what the client does with its hosts file.
2205 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
2211 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
2212 (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
2214 debug("client_input_global_request: rtype %s want_reply %d",
2216 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2217 success = client_input_hostkeys(ssh);
2219 if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS :
2220 SSH2_MSG_REQUEST_FAILURE)) != 0 ||
2221 (r = sshpkt_send(ssh)) != 0 ||
2222 (r = ssh_packet_write_wait(ssh)) != 0)
2232 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
2233 const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
2236 int i, j, matched, len, r;
2240 debug2("%s: id %d", __func__, id);
2242 if ((c = channel_lookup(ssh, id)) == NULL)
2243 fatal("%s: channel %d: unknown channel", __func__, id);
2245 ssh_packet_set_interactive(ssh, want_tty,
2246 options.ip_qos_interactive, options.ip_qos_bulk);
2251 /* Store window size in the packet. */
2252 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2253 memset(&ws, 0, sizeof(ws));
2255 channel_request_start(ssh, id, "pty-req", 1);
2256 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
2257 if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : ""))
2259 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
2260 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
2261 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
2262 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0)
2263 fatal("%s: build packet: %s", __func__, ssh_err(r));
2265 tiop = get_saved_tio();
2266 ssh_tty_make_modes(ssh, -1, tiop);
2267 if ((r = sshpkt_send(ssh)) != 0)
2268 fatal("%s: send packet: %s", __func__, ssh_err(r));
2269 /* XXX wait for reply */
2273 /* Transfer any environment variables from client to server */
2274 if (options.num_send_env != 0 && env != NULL) {
2275 debug("Sending environment.");
2276 for (i = 0; env[i] != NULL; i++) {
2278 name = xstrdup(env[i]);
2279 if ((val = strchr(name, '=')) == NULL) {
2286 for (j = 0; j < options.num_send_env; j++) {
2287 if (match_pattern(name, options.send_env[j])) {
2293 debug3("Ignored env %s", name);
2298 debug("Sending env %s = %s", name, val);
2299 channel_request_start(ssh, id, "env", 0);
2300 if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
2301 (r = sshpkt_put_cstring(ssh, val)) != 0 ||
2302 (r = sshpkt_send(ssh)) != 0) {
2303 fatal("%s: send packet: %s",
2304 __func__, ssh_err(r));
2309 for (i = 0; i < options.num_setenv; i++) {
2311 name = xstrdup(options.setenv[i]);
2312 if ((val = strchr(name, '=')) == NULL) {
2318 debug("Setting env %s = %s", name, val);
2319 channel_request_start(ssh, id, "env", 0);
2320 if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
2321 (r = sshpkt_put_cstring(ssh, val)) != 0 ||
2322 (r = sshpkt_send(ssh)) != 0)
2323 fatal("%s: send packet: %s", __func__, ssh_err(r));
2327 len = sshbuf_len(cmd);
2331 if (want_subsystem) {
2332 debug("Sending subsystem: %.*s",
2333 len, (const u_char*)sshbuf_ptr(cmd));
2334 channel_request_start(ssh, id, "subsystem", 1);
2335 client_expect_confirm(ssh, id, "subsystem",
2338 debug("Sending command: %.*s",
2339 len, (const u_char*)sshbuf_ptr(cmd));
2340 channel_request_start(ssh, id, "exec", 1);
2341 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
2343 if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 ||
2344 (r = sshpkt_send(ssh)) != 0)
2345 fatal("%s: send command: %s", __func__, ssh_err(r));
2347 channel_request_start(ssh, id, "shell", 1);
2348 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
2349 if ((r = sshpkt_send(ssh)) != 0) {
2350 fatal("%s: send shell request: %s",
2351 __func__, ssh_err(r));
2357 client_init_dispatch(struct ssh *ssh)
2359 ssh_dispatch_init(ssh, &dispatch_protocol_error);
2361 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2362 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2363 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2364 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2365 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2366 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2367 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2368 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2369 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2370 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2371 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2372 ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2375 ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
2377 /* global request reply messages */
2378 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2379 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2383 client_stop_mux(void)
2385 if (options.control_path != NULL && muxserver_sock != -1)
2386 unlink(options.control_path);
2388 * If we are in persist mode, or don't have a shell, signal that we
2389 * should close when all active channels are closed.
2391 if (options.control_persist || no_shell_flag) {
2393 setproctitle("[stopped mux]");
2397 /* client specific fatal cleanup */
2401 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2402 leave_non_blocking();
2403 if (options.control_path != NULL && muxserver_sock != -1)
2404 unlink(options.control_path);
2405 ssh_kill_proxy_command();