1 /* $OpenBSD: clientloop.c,v 1.291 2017/03/10 05:01:13 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"
102 #include "myproposal.h"
105 #include "readconf.h"
106 #include "clientloop.h"
107 #include "sshconnect.h"
109 #include "atomicio.h"
114 #include "hostfile.h"
117 extern Options options;
119 /* Flag indicating that stdin should be redirected from /dev/null. */
120 extern int stdin_null_flag;
122 /* Flag indicating that no shell has been requested */
123 extern int no_shell_flag;
125 /* Flag indicating that ssh should daemonise after authentication is complete */
126 extern int fork_after_authentication_flag;
129 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
132 * Name of the host we are connecting to. This is the name given on the
133 * command line, or the HostName specified for the user-supplied name in a
134 * configuration file.
139 * Flag to indicate that we have received a window change signal which has
140 * not yet been processed. This will cause a message indicating the new
141 * window size to be sent to the server a little later. This is volatile
142 * because this is updated in a signal handler.
144 static volatile sig_atomic_t received_window_change_signal = 0;
145 static volatile sig_atomic_t received_signal = 0;
147 /* Flag indicating whether the user's terminal is in non-blocking mode. */
148 static int in_non_blocking_mode = 0;
150 /* Time when backgrounded control master using ControlPersist should exit */
151 static time_t control_persist_exit_time = 0;
153 /* Common data for the client loop code. */
154 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
155 static int escape_char1; /* Escape character. (proto1 only) */
156 static int escape_pending1; /* Last character was an escape (proto1 only) */
157 static int last_was_cr; /* Last character was a newline. */
158 static int exit_status; /* Used to store the command exit status. */
159 static int stdin_eof; /* EOF has been encountered on stderr. */
160 static Buffer stdin_buffer; /* Buffer for stdin data. */
161 static Buffer stdout_buffer; /* Buffer for stdout data. */
162 static Buffer stderr_buffer; /* Buffer for stderr data. */
163 static u_int buffer_high; /* Soft max buffer size. */
164 static int connection_in; /* Connection to server (input). */
165 static int connection_out; /* Connection to server (output). */
166 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
167 static int session_closed; /* In SSH2: login session closed. */
168 static u_int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
170 static void client_init_dispatch(void);
171 int session_ident = -1;
173 /* Track escape per proto2 channel */
174 struct escape_filter_ctx {
179 /* Context for channel confirmation replies */
180 struct channel_reply_ctx {
181 const char *request_type;
183 enum confirm_action action;
186 /* Global request success/failure callbacks */
187 struct global_confirm {
188 TAILQ_ENTRY(global_confirm) entry;
189 global_confirm_cb *cb;
193 TAILQ_HEAD(global_confirms, global_confirm);
194 static struct global_confirms global_confirms =
195 TAILQ_HEAD_INITIALIZER(global_confirms);
197 void ssh_process_session2_setup(int, int, int, Buffer *);
199 /* Restores stdin to blocking mode. */
202 leave_non_blocking(void)
204 if (in_non_blocking_mode) {
205 unset_nonblock(fileno(stdin));
206 in_non_blocking_mode = 0;
210 /* Puts stdin terminal in non-blocking mode. */
213 enter_non_blocking(void)
215 in_non_blocking_mode = 1;
216 set_nonblock(fileno(stdin));
220 * Signal handler for the window change signal (SIGWINCH). This just sets a
221 * flag indicating that the window has changed.
225 window_change_handler(int sig)
227 received_window_change_signal = 1;
228 signal(SIGWINCH, window_change_handler);
232 * Signal handler for signals that cause the program to terminate. These
233 * signals must be trapped to restore terminal modes.
237 signal_handler(int sig)
239 received_signal = sig;
244 * Returns current time in seconds from Jan 1, 1970 with the maximum
245 * available resolution.
249 get_current_time(void)
252 gettimeofday(&tv, NULL);
253 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
257 * Sets control_persist_exit_time to the absolute time when the
258 * backgrounded control master should exit due to expiry of the
259 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
260 * control master process, or if there is no ControlPersist timeout.
263 set_control_persist_exit_time(void)
265 if (muxserver_sock == -1 || !options.control_persist
266 || options.control_persist_timeout == 0) {
267 /* not using a ControlPersist timeout */
268 control_persist_exit_time = 0;
269 } else if (channel_still_open()) {
270 /* some client connections are still open */
271 if (control_persist_exit_time > 0)
272 debug2("%s: cancel scheduled exit", __func__);
273 control_persist_exit_time = 0;
274 } else if (control_persist_exit_time <= 0) {
275 /* a client connection has recently closed */
276 control_persist_exit_time = monotime() +
277 (time_t)options.control_persist_timeout;
278 debug2("%s: schedule exit in %d seconds", __func__,
279 options.control_persist_timeout);
281 /* else we are already counting down to the timeout */
284 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
286 client_x11_display_valid(const char *display)
293 dlen = strlen(display);
294 for (i = 0; i < dlen; i++) {
295 if (!isalnum((u_char)display[i]) &&
296 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
297 debug("Invalid character '%c' in DISPLAY", display[i]);
304 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
305 #define X11_TIMEOUT_SLACK 60
307 client_x11_get_proto(const char *display, const char *xauth_path,
308 u_int trusted, u_int timeout, char **_proto, char **_data)
310 char cmd[1024], line[512], xdisplay[512];
311 char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
312 static char proto[512], data[512];
314 int got_data = 0, generated = 0, do_unlink = 0, r;
316 u_int now, x11_timeout_real;
320 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
322 if (!client_x11_display_valid(display)) {
324 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
328 if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
329 debug("No xauth program.");
333 if (xauth_path != NULL) {
335 * Handle FamilyLocal case where $DISPLAY does
336 * not match an authorization entry. For this we
337 * just try "xauth list unix:displaynum.screennum".
338 * XXX: "localhost" match to determine FamilyLocal
341 if (strncmp(display, "localhost:", 10) == 0) {
342 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
343 display + 10)) < 0 ||
344 (size_t)r >= sizeof(xdisplay)) {
345 error("%s: display name too long", __func__);
352 * Generate an untrusted X11 auth cookie.
354 * The authentication cookie should briefly outlive
355 * ssh's willingness to forward X11 connections to
356 * avoid nasty fail-open behaviour in the X server.
358 mktemp_proto(xauthdir, sizeof(xauthdir));
359 if (mkdtemp(xauthdir) == NULL) {
360 error("%s: mkdtemp: %s",
361 __func__, strerror(errno));
365 if ((r = snprintf(xauthfile, sizeof(xauthfile),
366 "%s/xauthfile", xauthdir)) < 0 ||
367 (size_t)r >= sizeof(xauthfile)) {
368 error("%s: xauthfile path too long", __func__);
374 if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK)
375 x11_timeout_real = UINT_MAX;
377 x11_timeout_real = timeout + X11_TIMEOUT_SLACK;
378 if ((r = snprintf(cmd, sizeof(cmd),
379 "%s -f %s generate %s " SSH_X11_PROTO
380 " untrusted timeout %u 2>" _PATH_DEVNULL,
381 xauth_path, xauthfile, display,
382 x11_timeout_real)) < 0 ||
383 (size_t)r >= sizeof(cmd))
384 fatal("%s: cmd too long", __func__);
385 debug2("%s: %s", __func__, cmd);
386 if (x11_refuse_time == 0) {
387 now = monotime() + 1;
388 if (UINT_MAX - timeout < now)
389 x11_refuse_time = UINT_MAX;
391 x11_refuse_time = now + timeout;
392 channel_set_x11_refuse_time(x11_refuse_time);
394 if (system(cmd) == 0)
399 * When in untrusted mode, we read the cookie only if it was
400 * successfully generated as an untrusted one in the step
403 if (trusted || generated) {
404 snprintf(cmd, sizeof(cmd),
405 "%s %s%s list %s 2>" _PATH_DEVNULL,
407 generated ? "-f " : "" ,
408 generated ? xauthfile : "",
410 debug2("x11_get_proto: %s", cmd);
412 if (f && fgets(line, sizeof(line), f) &&
413 sscanf(line, "%*s %511s %511s", proto, data) == 2)
425 /* Don't fall back to fake X11 data for untrusted forwarding */
426 if (!trusted && !got_data) {
427 error("Warning: untrusted X11 forwarding setup failed: "
428 "xauth key data not generated");
433 * If we didn't get authentication data, just make up some
434 * data. The forwarding code will check the validity of the
435 * response anyway, and substitute this data. The X11
436 * server, however, will ignore this fake data and use
437 * whatever authentication mechanisms it was using otherwise
438 * for the local connection.
444 logit("Warning: No xauth data; "
445 "using fake authentication data for X11 forwarding.");
446 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
447 arc4random_buf(rnd, sizeof(rnd));
448 for (i = 0; i < sizeof(rnd); i++) {
449 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
458 * This is called when the interactive is entered. This checks if there is
459 * an EOF coming on stdin. We must check this explicitly, as select() does
460 * not appear to wake up when redirecting from /dev/null.
464 client_check_initial_eof_on_stdin(void)
470 * If standard input is to be "redirected from /dev/null", we simply
471 * mark that we have seen an EOF and send an EOF message to the
472 * server. Otherwise, we try to read a single character; it appears
473 * that for some files, such /dev/null, select() never wakes up for
474 * read for this descriptor, which means that we never get EOF. This
475 * way we will get the EOF if stdin comes from /dev/null or similar.
477 if (stdin_null_flag) {
478 /* Fake EOF on stdin. */
479 debug("Sending eof.");
481 packet_start(SSH_CMSG_EOF);
484 enter_non_blocking();
486 /* Check for immediate EOF on stdin. */
487 len = read(fileno(stdin), buf, 1);
490 * EOF. Record that we have seen it and send
493 debug("Sending eof.");
495 packet_start(SSH_CMSG_EOF);
497 } else if (len > 0) {
499 * Got data. We must store the data in the buffer,
500 * and also process it as an escape character if
503 if ((u_char) buf[0] == escape_char1)
506 buffer_append(&stdin_buffer, buf, 1);
508 leave_non_blocking();
514 * Make packets from buffered stdin data, and buffer them for sending to the
519 client_make_packets_from_stdin_data(void)
523 /* Send buffered stdin data to the server. */
524 while (buffer_len(&stdin_buffer) > 0 &&
525 packet_not_very_much_data_to_write()) {
526 len = buffer_len(&stdin_buffer);
527 /* Keep the packets at reasonable size. */
528 if (len > packet_get_maxsize())
529 len = packet_get_maxsize();
530 packet_start(SSH_CMSG_STDIN_DATA);
531 packet_put_string(buffer_ptr(&stdin_buffer), len);
533 buffer_consume(&stdin_buffer, len);
534 /* If we have a pending EOF, send it now. */
535 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
536 packet_start(SSH_CMSG_EOF);
543 * Checks if the client window has changed, and sends a packet about it to
544 * the server if so. The actual change is detected elsewhere (by a software
545 * interrupt on Unix); this just checks the flag and sends a message if
550 client_check_window_change(void)
554 if (! received_window_change_signal)
557 received_window_change_signal = 0;
559 debug2("client_check_window_change: changed");
562 channel_send_window_changes();
564 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
566 packet_start(SSH_CMSG_WINDOW_SIZE);
567 packet_put_int((u_int)ws.ws_row);
568 packet_put_int((u_int)ws.ws_col);
569 packet_put_int((u_int)ws.ws_xpixel);
570 packet_put_int((u_int)ws.ws_ypixel);
576 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
578 struct global_confirm *gc;
580 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
583 gc->cb(type, seq, gc->ctx);
584 if (--gc->ref_count <= 0) {
585 TAILQ_REMOVE(&global_confirms, gc, entry);
586 explicit_bzero(gc, sizeof(*gc));
590 packet_set_alive_timeouts(0);
595 server_alive_check(void)
597 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
598 logit("Timeout, server %s not responding.", host);
601 packet_start(SSH2_MSG_GLOBAL_REQUEST);
602 packet_put_cstring("keepalive@openssh.com");
603 packet_put_char(1); /* boolean: want reply */
605 /* Insert an empty placeholder to maintain ordering */
606 client_register_global_confirm(NULL, NULL);
610 * Waits until the client can do something (some data becomes available on
611 * one of the file descriptors).
614 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
615 int *maxfdp, u_int *nallocp, int rekeying)
617 struct timeval tv, *tvp;
619 time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
622 /* Add any selections by the channel mechanism. */
623 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
624 &minwait_secs, rekeying);
627 /* Read from the connection, unless our buffers are full. */
628 if (buffer_len(&stdout_buffer) < buffer_high &&
629 buffer_len(&stderr_buffer) < buffer_high &&
630 channel_not_very_much_buffered_data())
631 FD_SET(connection_in, *readsetp);
633 * Read from stdin, unless we have seen EOF or have very much
634 * buffered data to send to the server.
636 if (!stdin_eof && packet_not_very_much_data_to_write())
637 FD_SET(fileno(stdin), *readsetp);
639 /* Select stdout/stderr if have data in buffer. */
640 if (buffer_len(&stdout_buffer) > 0)
641 FD_SET(fileno(stdout), *writesetp);
642 if (buffer_len(&stderr_buffer) > 0)
643 FD_SET(fileno(stderr), *writesetp);
645 /* channel_prepare_select could have closed the last channel */
646 if (session_closed && !channel_still_open() &&
647 !packet_have_data_to_write()) {
648 /* clear mask since we did not call select() */
649 memset(*readsetp, 0, *nallocp);
650 memset(*writesetp, 0, *nallocp);
653 FD_SET(connection_in, *readsetp);
657 /* Select server connection if have data to write to the server. */
658 if (packet_have_data_to_write())
659 FD_SET(connection_out, *writesetp);
662 * Wait for something to happen. This will suspend the process until
663 * some selected descriptor can be read, written, or has some other
664 * event pending, or a timeout expires.
667 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
668 if (options.server_alive_interval > 0 && compat20) {
669 timeout_secs = options.server_alive_interval;
670 server_alive_time = now + options.server_alive_interval;
672 if (options.rekey_interval > 0 && compat20 && !rekeying)
673 timeout_secs = MINIMUM(timeout_secs, packet_get_rekey_timeout());
674 set_control_persist_exit_time();
675 if (control_persist_exit_time > 0) {
676 timeout_secs = MINIMUM(timeout_secs,
677 control_persist_exit_time - now);
678 if (timeout_secs < 0)
681 if (minwait_secs != 0)
682 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
683 if (timeout_secs == INT_MAX)
686 tv.tv_sec = timeout_secs;
691 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
696 * We have to clear the select masks, because we return.
697 * We have to return, because the mainloop checks for the flags
698 * set by the signal handlers.
700 memset(*readsetp, 0, *nallocp);
701 memset(*writesetp, 0, *nallocp);
705 /* Note: we might still have data in the buffers. */
706 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
707 buffer_append(&stderr_buffer, buf, strlen(buf));
709 } else if (ret == 0) {
711 * Timeout. Could have been either keepalive or rekeying.
712 * Keepalive we check here, rekeying is checked in clientloop.
714 if (server_alive_time != 0 && server_alive_time <= monotime())
715 server_alive_check();
721 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
723 /* Flush stdout and stderr buffers. */
724 if (buffer_len(bout) > 0)
725 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
727 if (buffer_len(berr) > 0)
728 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
731 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
734 * Free (and clear) the buffer to reduce the amount of data that gets
741 /* Send the suspend signal to the program itself. */
742 kill(getpid(), SIGTSTP);
744 /* Reset window sizes in case they have changed */
745 received_window_change_signal = 1;
747 /* OK, we have been continued by the user. Reinitialize buffers. */
752 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
756 client_process_net_input(fd_set *readset)
759 char buf[SSH_IOBUFSZ];
762 * Read input from the server, and add any such data to the buffer of
763 * the packet subsystem.
765 if (FD_ISSET(connection_in, readset)) {
766 /* Read as much as possible. */
767 len = read(connection_in, buf, sizeof(buf));
770 * Received EOF. The remote host has closed the
773 snprintf(buf, sizeof buf,
774 "Connection to %.300s closed by remote host.\r\n",
776 buffer_append(&stderr_buffer, buf, strlen(buf));
781 * There is a kernel bug on Solaris that causes select to
782 * sometimes wake up even though there is no data available.
785 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
790 * An error has encountered. Perhaps there is a
793 snprintf(buf, sizeof buf,
794 "Read from remote host %.300s: %.100s\r\n",
795 host, strerror(errno));
796 buffer_append(&stderr_buffer, buf, strlen(buf));
800 packet_process_incoming(buf, len);
805 client_status_confirm(int type, Channel *c, void *ctx)
807 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
812 * If a TTY was explicitly requested, then a failure to allocate
815 if (cr->action == CONFIRM_TTY &&
816 (options.request_tty == REQUEST_TTY_FORCE ||
817 options.request_tty == REQUEST_TTY_YES))
818 cr->action = CONFIRM_CLOSE;
820 /* XXX supress on mux _client_ quietmode */
821 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
822 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
824 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
825 debug2("%s request accepted on channel %d",
826 cr->request_type, c->self);
827 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
829 snprintf(errmsg, sizeof(errmsg),
830 "%s request failed\r\n", cr->request_type);
832 snprintf(errmsg, sizeof(errmsg),
833 "%s request failed on channel %d",
834 cr->request_type, c->self);
836 /* If error occurred on primary session channel, then exit */
837 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
840 * If error occurred on mux client, append to
844 buffer_append(&c->extended, errmsg,
848 if (cr->action == CONFIRM_TTY) {
850 * If a TTY allocation error occurred, then arrange
851 * for the correct TTY to leave raw mode.
853 if (c->self == session_ident)
856 mux_tty_alloc_failed(c);
857 } else if (cr->action == CONFIRM_CLOSE) {
859 chan_write_failed(c);
866 client_abandon_status_confirm(Channel *c, void *ctx)
872 client_expect_confirm(int id, const char *request,
873 enum confirm_action action)
875 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
877 cr->request_type = request;
880 channel_register_status_confirm(id, client_status_confirm,
881 client_abandon_status_confirm, cr);
885 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
887 struct global_confirm *gc, *last_gc;
889 /* Coalesce identical callbacks */
890 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
891 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
892 if (++last_gc->ref_count >= INT_MAX)
893 fatal("%s: last_gc->ref_count = %d",
894 __func__, last_gc->ref_count);
898 gc = xcalloc(1, sizeof(*gc));
902 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
906 process_cmdline(void)
908 void (*handler)(int);
910 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
913 memset(&fwd, 0, sizeof(fwd));
915 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
916 handler = signal(SIGINT, SIG_IGN);
917 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
920 while (isspace((u_char)*s))
923 s++; /* Skip cmdline '-', if any */
927 if (*s == 'h' || *s == 'H' || *s == '?') {
929 logit(" -L[bind_address:]port:host:hostport "
930 "Request local forward");
931 logit(" -R[bind_address:]port:host:hostport "
932 "Request remote forward");
933 logit(" -D[bind_address:]port "
934 "Request dynamic forward");
935 logit(" -KL[bind_address:]port "
936 "Cancel local forward");
937 logit(" -KR[bind_address:]port "
938 "Cancel remote forward");
939 logit(" -KD[bind_address:]port "
940 "Cancel dynamic forward");
941 if (!options.permit_local_command)
944 "Execute local command");
948 if (*s == '!' && options.permit_local_command) {
965 logit("Invalid command.");
969 if (delete && !compat20) {
970 logit("Not supported for SSH protocol version 1.");
974 while (isspace((u_char)*++s))
977 /* XXX update list of forwards in options */
979 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
980 if (!parse_forward(&fwd, s, 1, 0)) {
981 logit("Bad forwarding close specification.");
985 ok = channel_request_rforward_cancel(&fwd) == 0;
987 ok = channel_cancel_lport_listener(&fwd,
988 0, &options.fwd_opts) > 0;
990 ok = channel_cancel_lport_listener(&fwd,
991 CHANNEL_CANCEL_PORT_STATIC,
992 &options.fwd_opts) > 0;
994 logit("Unknown port forwarding.");
997 logit("Canceled forwarding.");
999 if (!parse_forward(&fwd, s, dynamic, remote)) {
1000 logit("Bad forwarding specification.");
1003 if (local || dynamic) {
1004 if (!channel_setup_local_fwd_listener(&fwd,
1005 &options.fwd_opts)) {
1006 logit("Port forwarding failed.");
1010 if (channel_request_remote_forwarding(&fwd) < 0) {
1011 logit("Port forwarding failed.");
1015 logit("Forwarding port.");
1019 signal(SIGINT, handler);
1020 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1022 free(fwd.listen_host);
1023 free(fwd.listen_path);
1024 free(fwd.connect_host);
1025 free(fwd.connect_path);
1028 /* reasons to suppress output of an escape command in help output */
1029 #define SUPPRESS_NEVER 0 /* never suppress, always show */
1030 #define SUPPRESS_PROTO1 1 /* don't show in protocol 1 sessions */
1031 #define SUPPRESS_MUXCLIENT 2 /* don't show in mux client sessions */
1032 #define SUPPRESS_MUXMASTER 4 /* don't show in mux master sessions */
1033 #define SUPPRESS_SYSLOG 8 /* don't show when logging to syslog */
1034 struct escape_help_text {
1039 static struct escape_help_text esc_txt[] = {
1040 {".", "terminate session", SUPPRESS_MUXMASTER},
1041 {".", "terminate connection (and any multiplexed sessions)",
1042 SUPPRESS_MUXCLIENT},
1043 {"B", "send a BREAK to the remote system", SUPPRESS_PROTO1},
1044 {"C", "open a command line", SUPPRESS_MUXCLIENT},
1045 {"R", "request rekey", SUPPRESS_PROTO1},
1046 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1047 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1048 {"#", "list forwarded connections", SUPPRESS_NEVER},
1049 {"&", "background ssh (when waiting for connections to terminate)",
1050 SUPPRESS_MUXCLIENT},
1051 {"?", "this message", SUPPRESS_NEVER},
1055 print_escape_help(Buffer *b, int escape_char, int protocol2, int mux_client,
1058 unsigned int i, suppress_flags;
1061 snprintf(string, sizeof string, "%c?\r\n"
1062 "Supported escape sequences:\r\n", escape_char);
1063 buffer_append(b, string, strlen(string));
1065 suppress_flags = (protocol2 ? 0 : SUPPRESS_PROTO1) |
1066 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1067 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1068 (using_stderr ? 0 : SUPPRESS_SYSLOG);
1070 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1071 if (esc_txt[i].flags & suppress_flags)
1073 snprintf(string, sizeof string, " %c%-3s - %s\r\n",
1074 escape_char, esc_txt[i].cmd, esc_txt[i].text);
1075 buffer_append(b, string, strlen(string));
1078 snprintf(string, sizeof string,
1079 " %c%c - send the escape character by typing it twice\r\n"
1080 "(Note that escapes are only recognized immediately after "
1081 "newline.)\r\n", escape_char, escape_char);
1082 buffer_append(b, string, strlen(string));
1086 * Process the characters one by one, call with c==NULL for proto1 case.
1089 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
1098 int *escape_pendingp, escape_char;
1099 struct escape_filter_ctx *efc;
1102 escape_pendingp = &escape_pending1;
1103 escape_char = escape_char1;
1105 if (c->filter_ctx == NULL)
1107 efc = (struct escape_filter_ctx *)c->filter_ctx;
1108 escape_pendingp = &efc->escape_pending;
1109 escape_char = efc->escape_char;
1115 for (i = 0; i < (u_int)len; i++) {
1116 /* Get one character at a time. */
1119 if (*escape_pendingp) {
1120 /* We have previously seen an escape character. */
1121 /* Clear the flag now. */
1122 *escape_pendingp = 0;
1124 /* Process the escaped character. */
1127 /* Terminate the connection. */
1128 snprintf(string, sizeof string, "%c.\r\n",
1130 buffer_append(berr, string, strlen(string));
1132 if (c && c->ctl_chan != -1) {
1133 chan_read_failed(c);
1134 chan_write_failed(c);
1136 c->detach_user(c->self, NULL);
1137 c->type = SSH_CHANNEL_ABANDONED;
1138 buffer_clear(&c->input);
1146 /* XXX support this for mux clients */
1147 if (c && c->ctl_chan != -1) {
1151 snprintf(b, sizeof b, "^Z");
1153 snprintf(b, sizeof b, "%c", ch);
1154 snprintf(string, sizeof string,
1155 "%c%s escape not available to "
1156 "multiplexed sessions\r\n",
1158 buffer_append(berr, string,
1162 /* Suspend the program. Inform the user */
1163 snprintf(string, sizeof string,
1164 "%c^Z [suspend ssh]\r\n", escape_char);
1165 buffer_append(berr, string, strlen(string));
1167 /* Restore terminal modes and suspend. */
1168 client_suspend_self(bin, bout, berr);
1170 /* We have been continued. */
1175 snprintf(string, sizeof string,
1176 "%cB\r\n", escape_char);
1177 buffer_append(berr, string,
1179 channel_request_start(c->self,
1181 packet_put_int(1000);
1188 if (datafellows & SSH_BUG_NOREKEY)
1189 logit("Server does not "
1190 "support re-keying");
1199 if (c && c->ctl_chan != -1)
1201 if (!log_is_on_stderr()) {
1202 snprintf(string, sizeof string,
1203 "%c%c [Logging to syslog]\r\n",
1205 buffer_append(berr, string,
1209 if (ch == 'V' && options.log_level >
1211 log_change_level(--options.log_level);
1212 if (ch == 'v' && options.log_level <
1213 SYSLOG_LEVEL_DEBUG3)
1214 log_change_level(++options.log_level);
1215 snprintf(string, sizeof string,
1216 "%c%c [LogLevel %s]\r\n", escape_char, ch,
1217 log_level_name(options.log_level));
1218 buffer_append(berr, string, strlen(string));
1222 if (c && c->ctl_chan != -1)
1225 * Detach the program (continue to serve
1226 * connections, but put in background and no
1227 * more new connections).
1229 /* Restore tty modes. */
1231 options.request_tty == REQUEST_TTY_FORCE);
1233 /* Stop listening for new connections. */
1234 channel_stop_listening();
1236 snprintf(string, sizeof string,
1237 "%c& [backgrounded]\n", escape_char);
1238 buffer_append(berr, string, strlen(string));
1240 /* Fork into background. */
1243 error("fork: %.100s", strerror(errno));
1246 if (pid != 0) { /* This is the parent. */
1247 /* The parent just exits. */
1250 /* The child continues serving connections. */
1252 buffer_append(bin, "\004", 1);
1253 /* fake EOF on stdin */
1255 } else if (!stdin_eof) {
1257 * Sending SSH_CMSG_EOF alone does not
1258 * always appear to be enough. So we
1259 * try to send an EOF character first.
1261 packet_start(SSH_CMSG_STDIN_DATA);
1262 packet_put_string("\004", 1);
1266 if (buffer_len(bin) == 0) {
1267 packet_start(SSH_CMSG_EOF);
1274 print_escape_help(berr, escape_char, compat20,
1275 (c && c->ctl_chan != -1),
1276 log_is_on_stderr());
1280 snprintf(string, sizeof string, "%c#\r\n",
1282 buffer_append(berr, string, strlen(string));
1283 s = channel_open_message();
1284 buffer_append(berr, s, strlen(s));
1289 if (c && c->ctl_chan != -1)
1295 if (ch != escape_char) {
1296 buffer_put_char(bin, escape_char);
1299 /* Escaped characters fall through here */
1304 * The previous character was not an escape char.
1305 * Check if this is an escape.
1307 if (last_was_cr && ch == escape_char) {
1309 * It is. Set the flag and continue to
1312 *escape_pendingp = 1;
1318 * Normal character. Record whether it was a newline,
1319 * and append it to the buffer.
1321 last_was_cr = (ch == '\r' || ch == '\n');
1322 buffer_put_char(bin, ch);
1329 client_process_input(fd_set *readset)
1332 char buf[SSH_IOBUFSZ];
1334 /* Read input from stdin. */
1335 if (FD_ISSET(fileno(stdin), readset)) {
1336 /* Read as much as possible. */
1337 len = read(fileno(stdin), buf, sizeof(buf));
1339 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1340 return; /* we'll try again later */
1343 * Received EOF or error. They are treated
1344 * similarly, except that an error message is printed
1345 * if it was an error condition.
1348 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1350 buffer_append(&stderr_buffer, buf, strlen(buf));
1352 /* Mark that we have seen EOF. */
1355 * Send an EOF message to the server unless there is
1356 * data in the buffer. If there is data in the
1357 * buffer, no message will be sent now. Code
1358 * elsewhere will send the EOF when the buffer
1359 * becomes empty if stdin_eof is set.
1361 if (buffer_len(&stdin_buffer) == 0) {
1362 packet_start(SSH_CMSG_EOF);
1365 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1367 * Normal successful read, and no escape character.
1368 * Just append the data to buffer.
1370 buffer_append(&stdin_buffer, buf, len);
1373 * Normal, successful read. But we have an escape
1374 * character and have to process the characters one
1377 if (process_escapes(NULL, &stdin_buffer,
1378 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1385 client_process_output(fd_set *writeset)
1390 /* Write buffered output to stdout. */
1391 if (FD_ISSET(fileno(stdout), writeset)) {
1392 /* Write as much data as possible. */
1393 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1394 buffer_len(&stdout_buffer));
1396 if (errno == EINTR || errno == EAGAIN ||
1397 errno == EWOULDBLOCK)
1401 * An error or EOF was encountered. Put an
1402 * error message to stderr buffer.
1404 snprintf(buf, sizeof buf,
1405 "write stdout: %.50s\r\n", strerror(errno));
1406 buffer_append(&stderr_buffer, buf, strlen(buf));
1411 /* Consume printed data from the buffer. */
1412 buffer_consume(&stdout_buffer, len);
1414 /* Write buffered output to stderr. */
1415 if (FD_ISSET(fileno(stderr), writeset)) {
1416 /* Write as much data as possible. */
1417 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1418 buffer_len(&stderr_buffer));
1420 if (errno == EINTR || errno == EAGAIN ||
1421 errno == EWOULDBLOCK)
1425 * EOF or error, but can't even print
1432 /* Consume printed characters from the buffer. */
1433 buffer_consume(&stderr_buffer, len);
1438 * Get packets from the connection input buffer, and process them as long as
1439 * there are packets available.
1441 * Any unknown packets received during the actual
1442 * session cause the session to terminate. This is
1443 * intended to make debugging easier since no
1444 * confirmations are sent. Any compatible protocol
1445 * extensions must be negotiated during the
1446 * preparatory phase.
1450 client_process_buffered_input_packets(void)
1452 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, active_state);
1455 /* scan buf[] for '~' before sending data to the peer */
1457 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1459 client_new_escape_filter_ctx(int escape_char)
1461 struct escape_filter_ctx *ret;
1463 ret = xcalloc(1, sizeof(*ret));
1464 ret->escape_pending = 0;
1465 ret->escape_char = escape_char;
1469 /* Free the escape filter context on channel free */
1471 client_filter_cleanup(int cid, void *ctx)
1477 client_simple_escape_filter(Channel *c, char *buf, int len)
1479 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1482 return process_escapes(c, &c->input, &c->output, &c->extended,
1487 client_channel_closed(int id, void *arg)
1489 channel_cancel_cleanup(id);
1491 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1495 * Implements the interactive session with the server. This is called after
1496 * the user has been authenticated, and a command has been started on the
1497 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1498 * used as an escape character for terminating or suspending the session.
1502 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1504 fd_set *readset = NULL, *writeset = NULL;
1505 double start_time, total_time;
1506 int r, max_fd = 0, max_fd2 = 0, len;
1507 u_int64_t ibytes, obytes;
1511 debug("Entering interactive session.");
1513 if (options.control_master &&
1514 !option_clear_or_none(options.control_path)) {
1515 debug("pledge: id");
1516 if (pledge("stdio rpath wpath cpath unix inet dns recvfd proc exec id tty",
1518 fatal("%s pledge(): %s", __func__, strerror(errno));
1520 } else if (options.forward_x11 || options.permit_local_command) {
1521 debug("pledge: exec");
1522 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1524 fatal("%s pledge(): %s", __func__, strerror(errno));
1526 } else if (options.update_hostkeys) {
1527 debug("pledge: filesystem full");
1528 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1530 fatal("%s pledge(): %s", __func__, strerror(errno));
1532 } else if (!option_clear_or_none(options.proxy_command) ||
1533 fork_after_authentication_flag) {
1534 debug("pledge: proc");
1535 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1536 fatal("%s pledge(): %s", __func__, strerror(errno));
1539 debug("pledge: network");
1540 if (pledge("stdio unix inet dns tty", NULL) == -1)
1541 fatal("%s pledge(): %s", __func__, strerror(errno));
1544 start_time = get_current_time();
1546 /* Initialize variables. */
1547 escape_pending1 = 0;
1551 buffer_high = 64 * 1024;
1552 connection_in = packet_get_connection_in();
1553 connection_out = packet_get_connection_out();
1554 max_fd = MAXIMUM(connection_in, connection_out);
1557 /* enable nonblocking unless tty */
1558 if (!isatty(fileno(stdin)))
1559 set_nonblock(fileno(stdin));
1560 if (!isatty(fileno(stdout)))
1561 set_nonblock(fileno(stdout));
1562 if (!isatty(fileno(stderr)))
1563 set_nonblock(fileno(stderr));
1564 max_fd = MAXIMUM(max_fd, fileno(stdin));
1565 max_fd = MAXIMUM(max_fd, fileno(stdout));
1566 max_fd = MAXIMUM(max_fd, fileno(stderr));
1569 escape_char1 = escape_char_arg;
1571 /* Initialize buffers. */
1572 buffer_init(&stdin_buffer);
1573 buffer_init(&stdout_buffer);
1574 buffer_init(&stderr_buffer);
1576 client_init_dispatch();
1579 * Set signal handlers, (e.g. to restore non-blocking mode)
1580 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1582 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1583 signal(SIGHUP, signal_handler);
1584 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1585 signal(SIGINT, signal_handler);
1586 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1587 signal(SIGQUIT, signal_handler);
1588 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1589 signal(SIGTERM, signal_handler);
1590 signal(SIGWINCH, window_change_handler);
1593 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1596 session_ident = ssh2_chan_id;
1597 if (session_ident != -1) {
1598 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1599 channel_register_filter(session_ident,
1600 client_simple_escape_filter, NULL,
1601 client_filter_cleanup,
1602 client_new_escape_filter_ctx(
1605 channel_register_cleanup(session_ident,
1606 client_channel_closed, 0);
1609 /* Check if we should immediately send eof on stdin. */
1610 client_check_initial_eof_on_stdin();
1613 /* Main loop of the client for the interactive session mode. */
1614 while (!quit_pending) {
1616 /* Process buffered packets sent by the server. */
1617 client_process_buffered_input_packets();
1619 if (compat20 && session_closed && !channel_still_open())
1622 if (ssh_packet_is_rekeying(active_state)) {
1623 debug("rekeying in progress");
1624 } else if (need_rekeying) {
1625 /* manual rekey request */
1626 debug("need rekeying");
1627 if ((r = kex_start_rekex(active_state)) != 0)
1628 fatal("%s: kex_start_rekex: %s", __func__,
1633 * Make packets of buffered stdin data, and buffer
1634 * them for sending to the server.
1637 client_make_packets_from_stdin_data();
1640 * Make packets from buffered channel data, and
1641 * enqueue them for sending to the server.
1643 if (packet_not_very_much_data_to_write())
1644 channel_output_poll();
1647 * Check if the window size has changed, and buffer a
1648 * message about it to the server if so.
1650 client_check_window_change();
1656 * Wait until we have something to do (something becomes
1657 * available on one of the descriptors).
1660 client_wait_until_can_do_something(&readset, &writeset,
1661 &max_fd2, &nalloc, ssh_packet_is_rekeying(active_state));
1666 /* Do channel operations unless rekeying in progress. */
1667 if (!ssh_packet_is_rekeying(active_state))
1668 channel_after_select(readset, writeset);
1670 /* Buffer input from the connection. */
1671 client_process_net_input(readset);
1677 /* Buffer data from stdin */
1678 client_process_input(readset);
1680 * Process output to stdout and stderr. Output to
1681 * the connection is processed elsewhere (above).
1683 client_process_output(writeset);
1687 * Send as much buffered packet data as possible to the
1690 if (FD_ISSET(connection_out, writeset))
1691 packet_write_poll();
1694 * If we are a backgrounded control master, and the
1695 * timeout has expired without any active client
1696 * connections, then quit.
1698 if (control_persist_exit_time > 0) {
1699 if (monotime() >= control_persist_exit_time) {
1700 debug("ControlPersist timeout expired");
1708 /* Terminate the session. */
1710 /* Stop watching for window change. */
1711 signal(SIGWINCH, SIG_DFL);
1714 packet_start(SSH2_MSG_DISCONNECT);
1715 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1716 packet_put_cstring("disconnected by user");
1717 packet_put_cstring(""); /* language tag */
1719 packet_write_wait();
1725 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1727 /* restore blocking io */
1728 if (!isatty(fileno(stdin)))
1729 unset_nonblock(fileno(stdin));
1730 if (!isatty(fileno(stdout)))
1731 unset_nonblock(fileno(stdout));
1732 if (!isatty(fileno(stderr)))
1733 unset_nonblock(fileno(stderr));
1736 * If there was no shell or command requested, there will be no remote
1737 * exit status to be returned. In that case, clear error code if the
1738 * connection was deliberately terminated at this end.
1740 if (no_shell_flag && received_signal == SIGTERM) {
1741 received_signal = 0;
1745 if (received_signal)
1746 fatal("Killed by signal %d.", (int) received_signal);
1749 * In interactive mode (with pseudo tty) display a message indicating
1750 * that the connection has been closed.
1752 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1753 snprintf(buf, sizeof buf,
1754 "Connection to %.64s closed.\r\n", host);
1755 buffer_append(&stderr_buffer, buf, strlen(buf));
1758 /* Output any buffered data for stdout. */
1759 if (buffer_len(&stdout_buffer) > 0) {
1760 len = atomicio(vwrite, fileno(stdout),
1761 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1762 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1763 error("Write failed flushing stdout buffer.");
1765 buffer_consume(&stdout_buffer, len);
1768 /* Output any buffered data for stderr. */
1769 if (buffer_len(&stderr_buffer) > 0) {
1770 len = atomicio(vwrite, fileno(stderr),
1771 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1772 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1773 error("Write failed flushing stderr buffer.");
1775 buffer_consume(&stderr_buffer, len);
1778 /* Clear and free any buffers. */
1779 explicit_bzero(buf, sizeof(buf));
1780 buffer_free(&stdin_buffer);
1781 buffer_free(&stdout_buffer);
1782 buffer_free(&stderr_buffer);
1784 /* Report bytes transferred, and transfer rates. */
1785 total_time = get_current_time() - start_time;
1786 packet_get_bytes(&ibytes, &obytes);
1787 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1788 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1790 verbose("Bytes per second: sent %.1f, received %.1f",
1791 obytes / total_time, ibytes / total_time);
1792 /* Return the exit status of the program. */
1793 debug("Exit status %d", exit_status);
1800 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1803 char *data = packet_get_string(&data_len);
1805 buffer_append(&stdout_buffer, data, data_len);
1806 explicit_bzero(data, data_len);
1811 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1814 char *data = packet_get_string(&data_len);
1816 buffer_append(&stderr_buffer, data, data_len);
1817 explicit_bzero(data, data_len);
1822 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1824 exit_status = packet_get_int();
1826 /* Acknowledge the exit. */
1827 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1830 * Must wait for packet to be sent since we are
1833 packet_write_wait();
1834 /* Flag that we want to exit. */
1840 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1843 int r, remote_id, sock;
1845 /* Read the remote channel number from the message. */
1846 remote_id = packet_get_int();
1850 * Get a connection to the local authentication agent (this may again
1853 if ((r = ssh_get_authentication_socket(&sock)) != 0 &&
1854 r != SSH_ERR_AGENT_NOT_PRESENT)
1855 debug("%s: ssh_get_authentication_socket: %s",
1856 __func__, ssh_err(r));
1860 * If we could not connect the agent, send an error message back to
1861 * the server. This should never happen unless the agent dies,
1862 * because authentication forwarding is only enabled if we have an
1866 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1867 -1, 0, 0, 0, "authentication agent connection", 1);
1868 c->remote_id = remote_id;
1872 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1873 packet_put_int(remote_id);
1875 /* Send a confirmation to the remote host. */
1876 debug("Forwarding authentication connection.");
1877 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1878 packet_put_int(remote_id);
1879 packet_put_int(c->self);
1886 client_request_forwarded_tcpip(const char *request_type, int rchan,
1887 u_int rwindow, u_int rmaxpack)
1890 struct sshbuf *b = NULL;
1891 char *listen_address, *originator_address;
1892 u_short listen_port, originator_port;
1895 /* Get rest of the packet */
1896 listen_address = packet_get_string(NULL);
1897 listen_port = packet_get_int();
1898 originator_address = packet_get_string(NULL);
1899 originator_port = packet_get_int();
1902 debug("%s: listen %s port %d, originator %s port %d", __func__,
1903 listen_address, listen_port, originator_address, originator_port);
1905 c = channel_connect_by_listen_address(listen_address, listen_port,
1906 "forwarded-tcpip", originator_address);
1908 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1909 if ((b = sshbuf_new()) == NULL) {
1910 error("%s: alloc reply", __func__);
1913 /* reconstruct and send to muxclient */
1914 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1915 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1916 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1917 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1918 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1919 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1920 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1921 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1922 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1923 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1924 (r = sshbuf_put_stringb(&c->output, b)) != 0) {
1925 error("%s: compose for muxclient %s", __func__,
1933 free(originator_address);
1934 free(listen_address);
1939 client_request_forwarded_streamlocal(const char *request_type, int rchan)
1944 /* Get the remote path. */
1945 listen_path = packet_get_string(NULL);
1946 /* XXX: Skip reserved field for now. */
1947 if (packet_get_string_ptr(NULL) == NULL)
1948 fatal("%s: packet_get_string_ptr failed", __func__);
1951 debug("%s: %s", __func__, listen_path);
1953 c = channel_connect_by_listen_path(listen_path,
1954 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1960 client_request_x11(const char *request_type, int rchan)
1964 u_short originator_port;
1967 if (!options.forward_x11) {
1968 error("Warning: ssh server tried X11 forwarding.");
1969 error("Warning: this is probably a break-in attempt by a "
1970 "malicious server.");
1973 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1974 verbose("Rejected X11 connection after ForwardX11Timeout "
1978 originator = packet_get_string(NULL);
1979 if (datafellows & SSH_BUG_X11FWD) {
1980 debug2("buggy server: x11 request w/o originator_port");
1981 originator_port = 0;
1983 originator_port = packet_get_int();
1986 /* XXX check permission */
1987 debug("client_request_x11: request from %s %d", originator,
1990 sock = x11_connect_display();
1993 c = channel_new("x11",
1994 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1995 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
2001 client_request_agent(const char *request_type, int rchan)
2006 if (!options.forward_agent) {
2007 error("Warning: ssh server tried agent forwarding.");
2008 error("Warning: this is probably a break-in attempt by a "
2009 "malicious server.");
2012 if ((r = ssh_get_authentication_socket(&sock)) != 0) {
2013 if (r != SSH_ERR_AGENT_NOT_PRESENT)
2014 debug("%s: ssh_get_authentication_socket: %s",
2015 __func__, ssh_err(r));
2018 c = channel_new("authentication agent connection",
2019 SSH_CHANNEL_OPEN, sock, sock, -1,
2020 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
2021 "authentication agent connection", 1);
2027 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
2032 if (tun_mode == SSH_TUNMODE_NO)
2036 error("Tunnel forwarding is not supported for protocol 1");
2040 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
2042 /* Open local tunnel device */
2043 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
2044 error("Tunnel device open failed.");
2048 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
2049 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
2052 #if defined(SSH_TUN_FILTER)
2053 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
2054 channel_register_filter(c->self, sys_tun_infilter,
2055 sys_tun_outfilter, NULL, NULL);
2058 packet_start(SSH2_MSG_CHANNEL_OPEN);
2059 packet_put_cstring("tun@openssh.com");
2060 packet_put_int(c->self);
2061 packet_put_int(c->local_window_max);
2062 packet_put_int(c->local_maxpacket);
2063 packet_put_int(tun_mode);
2064 packet_put_int(remote_tun);
2070 /* XXXX move to generic input handler */
2072 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
2077 u_int rmaxpack, rwindow, len;
2079 ctype = packet_get_string(&len);
2080 rchan = packet_get_int();
2081 rwindow = packet_get_int();
2082 rmaxpack = packet_get_int();
2084 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
2085 ctype, rchan, rwindow, rmaxpack);
2087 if (strcmp(ctype, "forwarded-tcpip") == 0) {
2088 c = client_request_forwarded_tcpip(ctype, rchan, rwindow,
2090 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
2091 c = client_request_forwarded_streamlocal(ctype, rchan);
2092 } else if (strcmp(ctype, "x11") == 0) {
2093 c = client_request_x11(ctype, rchan);
2094 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
2095 c = client_request_agent(ctype, rchan);
2097 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
2098 debug3("proxied to downstream: %s", ctype);
2099 } else if (c != NULL) {
2100 debug("confirm %s", ctype);
2101 c->remote_id = rchan;
2102 c->remote_window = rwindow;
2103 c->remote_maxpacket = rmaxpack;
2104 if (c->type != SSH_CHANNEL_CONNECTING) {
2105 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
2106 packet_put_int(c->remote_id);
2107 packet_put_int(c->self);
2108 packet_put_int(c->local_window);
2109 packet_put_int(c->local_maxpacket);
2113 debug("failure %s", ctype);
2114 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
2115 packet_put_int(rchan);
2116 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
2117 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2118 packet_put_cstring("open failed");
2119 packet_put_cstring("");
2128 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
2131 int exitval, id, reply, success = 0;
2134 id = packet_get_int();
2135 c = channel_lookup(id);
2136 if (channel_proxy_upstream(c, type, seq, ctxt))
2138 rtype = packet_get_string(NULL);
2139 reply = packet_get_char();
2141 debug("client_input_channel_req: channel %d rtype %s reply %d",
2145 error("client_input_channel_req: request for channel -1");
2146 } else if (c == NULL) {
2147 error("client_input_channel_req: channel %d: "
2148 "unknown channel", id);
2149 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
2152 } else if (strcmp(rtype, "exit-status") == 0) {
2153 exitval = packet_get_int();
2154 if (c->ctl_chan != -1) {
2155 mux_exit_message(c, exitval);
2157 } else if (id == session_ident) {
2158 /* Record exit value of local session */
2160 exit_status = exitval;
2162 /* Probably for a mux channel that has already closed */
2163 debug("%s: no sink for exit-status on channel %d",
2168 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
2169 packet_start(success ?
2170 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
2171 packet_put_int(c->remote_id);
2178 struct hostkeys_update_ctx {
2179 /* The hostname and (optionally) IP address string for the server */
2180 char *host_str, *ip_str;
2183 * Keys received from the server and a flag for each indicating
2184 * whether they already exist in known_hosts.
2185 * keys_seen is filled in by hostkeys_find() and later (for new
2186 * keys) by client_global_hostkeys_private_confirm().
2188 struct sshkey **keys;
2195 * Keys that are in known_hosts, but were not present in the update
2196 * from the server (i.e. scheduled to be deleted).
2197 * Filled in by hostkeys_find().
2199 struct sshkey **old_keys;
2204 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
2210 for (i = 0; i < ctx->nkeys; i++)
2211 sshkey_free(ctx->keys[i]);
2213 free(ctx->keys_seen);
2214 for (i = 0; i < ctx->nold; i++)
2215 sshkey_free(ctx->old_keys[i]);
2216 free(ctx->old_keys);
2217 free(ctx->host_str);
2223 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
2225 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2227 struct sshkey **tmp;
2229 if (l->status != HKF_STATUS_MATCHED || l->key == NULL ||
2230 l->key->type == KEY_RSA1)
2233 /* Mark off keys we've already seen for this host */
2234 for (i = 0; i < ctx->nkeys; i++) {
2235 if (sshkey_equal(l->key, ctx->keys[i])) {
2236 debug3("%s: found %s key at %s:%ld", __func__,
2237 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
2238 ctx->keys_seen[i] = 1;
2242 /* This line contained a key that not offered by the server */
2243 debug3("%s: deprecated %s key at %s:%ld", __func__,
2244 sshkey_ssh_name(l->key), l->path, l->linenum);
2245 if ((tmp = reallocarray(ctx->old_keys, ctx->nold + 1,
2246 sizeof(*ctx->old_keys))) == NULL)
2247 fatal("%s: reallocarray failed nold = %zu",
2248 __func__, ctx->nold);
2249 ctx->old_keys = tmp;
2250 ctx->old_keys[ctx->nold++] = l->key;
2257 update_known_hosts(struct hostkeys_update_ctx *ctx)
2260 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
2261 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
2262 char *fp, *response;
2265 for (i = 0; i < ctx->nkeys; i++) {
2266 if (ctx->keys_seen[i] != 2)
2268 if ((fp = sshkey_fingerprint(ctx->keys[i],
2269 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2270 fatal("%s: sshkey_fingerprint failed", __func__);
2271 do_log2(loglevel, "Learned new hostkey: %s %s",
2272 sshkey_type(ctx->keys[i]), fp);
2275 for (i = 0; i < ctx->nold; i++) {
2276 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
2277 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2278 fatal("%s: sshkey_fingerprint failed", __func__);
2279 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
2280 sshkey_type(ctx->old_keys[i]), fp);
2283 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
2284 if (get_saved_tio() != NULL) {
2289 for (i = 0; !quit_pending && i < 3; i++) {
2291 response = read_passphrase("Accept updated hostkeys? "
2292 "(yes/no): ", RP_ECHO);
2293 if (strcasecmp(response, "yes") == 0)
2295 else if (quit_pending || response == NULL ||
2296 strcasecmp(response, "no") == 0) {
2297 options.update_hostkeys = 0;
2300 do_log2(loglevel, "Please enter "
2301 "\"yes\" or \"no\"");
2304 if (quit_pending || i >= 3 || response == NULL)
2305 options.update_hostkeys = 0;
2312 * Now that all the keys are verified, we can go ahead and replace
2313 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
2314 * cancel the operation).
2316 if (options.update_hostkeys != 0 &&
2317 (r = hostfile_replace_entries(options.user_hostfiles[0],
2318 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
2319 options.hash_known_hosts, 0,
2320 options.fingerprint_hash)) != 0)
2321 error("%s: hostfile_replace_entries failed: %s",
2322 __func__, ssh_err(r));
2326 client_global_hostkeys_private_confirm(int type, u_int32_t seq, void *_ctx)
2328 struct ssh *ssh = active_state; /* XXX */
2329 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2331 struct sshbuf *signdata;
2337 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
2338 if (type != SSH2_MSG_REQUEST_SUCCESS) {
2339 error("Server failed to confirm ownership of "
2340 "private host keys");
2341 hostkeys_update_ctx_free(ctx);
2344 if ((signdata = sshbuf_new()) == NULL)
2345 fatal("%s: sshbuf_new failed", __func__);
2346 /* Don't want to accidentally accept an unbound signature */
2347 if (ssh->kex->session_id_len == 0)
2348 fatal("%s: ssh->kex->session_id_len == 0", __func__);
2350 * Expect a signature for each of the ctx->nnew private keys we
2351 * haven't seen before. They will be in the same order as the
2352 * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
2354 for (ndone = i = 0; i < ctx->nkeys; i++) {
2355 if (ctx->keys_seen[i])
2357 /* Prepare data to be signed: session ID, unique string, key */
2358 sshbuf_reset(signdata);
2359 if ( (r = sshbuf_put_cstring(signdata,
2360 "hostkeys-prove-00@openssh.com")) != 0 ||
2361 (r = sshbuf_put_string(signdata, ssh->kex->session_id,
2362 ssh->kex->session_id_len)) != 0 ||
2363 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
2364 fatal("%s: failed to prepare signature: %s",
2365 __func__, ssh_err(r));
2366 /* Extract and verify signature */
2367 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
2368 error("%s: couldn't parse message: %s",
2369 __func__, ssh_err(r));
2372 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
2373 sshbuf_ptr(signdata), sshbuf_len(signdata), 0)) != 0) {
2374 error("%s: server gave bad signature for %s key %zu",
2375 __func__, sshkey_type(ctx->keys[i]), i);
2378 /* Key is good. Mark it as 'seen' */
2379 ctx->keys_seen[i] = 2;
2382 if (ndone != ctx->nnew)
2383 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
2384 ndone, ctx->nnew); /* Shouldn't happen */
2385 ssh_packet_check_eom(ssh);
2387 /* Make the edits to known_hosts */
2388 update_known_hosts(ctx);
2390 hostkeys_update_ctx_free(ctx);
2394 * Returns non-zero if the key is accepted by HostkeyAlgorithms.
2395 * Made slightly less trivial by the multiple RSA signature algorithm names.
2398 key_accepted_by_hostkeyalgs(const struct sshkey *key)
2400 const char *ktype = sshkey_ssh_name(key);
2401 const char *hostkeyalgs = options.hostkeyalgorithms != NULL ?
2402 options.hostkeyalgorithms : KEX_DEFAULT_PK_ALG;
2404 if (key == NULL || key->type == KEY_UNSPEC)
2406 if (key->type == KEY_RSA &&
2407 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
2408 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
2410 return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
2414 * Handle hostkeys-00@openssh.com global request to inform the client of all
2415 * the server's hostkeys. The keys are checked against the user's
2416 * HostkeyAlgorithms preference before they are accepted.
2419 client_input_hostkeys(void)
2421 struct ssh *ssh = active_state; /* XXX */
2422 const u_char *blob = NULL;
2424 struct sshbuf *buf = NULL;
2425 struct sshkey *key = NULL, **tmp;
2428 static int hostkeys_seen = 0; /* XXX use struct ssh */
2429 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2430 struct hostkeys_update_ctx *ctx = NULL;
2433 fatal("%s: server already sent hostkeys", __func__);
2434 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2436 return 1; /* won't ask in batchmode, so don't even try */
2437 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2440 ctx = xcalloc(1, sizeof(*ctx));
2441 while (ssh_packet_remaining(ssh) > 0) {
2444 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2445 error("%s: couldn't parse message: %s",
2446 __func__, ssh_err(r));
2449 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2450 error("%s: parse key: %s", __func__, ssh_err(r));
2453 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2455 debug3("%s: received %s key %s", __func__,
2456 sshkey_type(key), fp);
2459 if (!key_accepted_by_hostkeyalgs(key)) {
2460 debug3("%s: %s key not permitted by HostkeyAlgorithms",
2461 __func__, sshkey_ssh_name(key));
2465 if (sshkey_is_cert(key)) {
2466 debug3("%s: %s key is a certificate; skipping",
2467 __func__, sshkey_ssh_name(key));
2470 /* Ensure keys are unique */
2471 for (i = 0; i < ctx->nkeys; i++) {
2472 if (sshkey_equal(key, ctx->keys[i])) {
2473 error("%s: received duplicated %s host key",
2474 __func__, sshkey_ssh_name(key));
2478 /* Key is good, record it */
2479 if ((tmp = reallocarray(ctx->keys, ctx->nkeys + 1,
2480 sizeof(*ctx->keys))) == NULL)
2481 fatal("%s: reallocarray failed nkeys = %zu",
2482 __func__, ctx->nkeys);
2484 ctx->keys[ctx->nkeys++] = key;
2488 if (ctx->nkeys == 0) {
2489 debug("%s: server sent no hostkeys", __func__);
2493 if ((ctx->keys_seen = calloc(ctx->nkeys,
2494 sizeof(*ctx->keys_seen))) == NULL)
2495 fatal("%s: calloc failed", __func__);
2497 get_hostfile_hostname_ipaddr(host,
2498 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2499 options.port, &ctx->host_str,
2500 options.check_host_ip ? &ctx->ip_str : NULL);
2502 /* Find which keys we already know about. */
2503 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2504 ctx, ctx->host_str, ctx->ip_str,
2505 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2506 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
2510 /* Figure out if we have any new keys to add */
2512 for (i = 0; i < ctx->nkeys; i++) {
2513 if (!ctx->keys_seen[i])
2517 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2518 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2520 if (ctx->nnew == 0 && ctx->nold != 0) {
2521 /* We have some keys to remove. Just do it. */
2522 update_known_hosts(ctx);
2523 } else if (ctx->nnew != 0) {
2525 * We have received hitherto-unseen keys from the server.
2526 * Ask the server to confirm ownership of the private halves.
2528 debug3("%s: asking server to prove ownership for %zu keys",
2529 __func__, ctx->nnew);
2530 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2531 (r = sshpkt_put_cstring(ssh,
2532 "hostkeys-prove-00@openssh.com")) != 0 ||
2533 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2534 fatal("%s: cannot prepare packet: %s",
2535 __func__, ssh_err(r));
2536 if ((buf = sshbuf_new()) == NULL)
2537 fatal("%s: sshbuf_new", __func__);
2538 for (i = 0; i < ctx->nkeys; i++) {
2539 if (ctx->keys_seen[i])
2542 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2543 fatal("%s: sshkey_putb: %s",
2544 __func__, ssh_err(r));
2545 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2546 fatal("%s: sshpkt_put_string: %s",
2547 __func__, ssh_err(r));
2549 if ((r = sshpkt_send(ssh)) != 0)
2550 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2551 client_register_global_confirm(
2552 client_global_hostkeys_private_confirm, ctx);
2553 ctx = NULL; /* will be freed in callback */
2558 hostkeys_update_ctx_free(ctx);
2562 * NB. Return success for all cases. The server doesn't need to know
2563 * what the client does with its hosts file.
2569 client_input_global_request(int type, u_int32_t seq, void *ctxt)
2575 rtype = packet_get_cstring(NULL);
2576 want_reply = packet_get_char();
2577 debug("client_input_global_request: rtype %s want_reply %d",
2579 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2580 success = client_input_hostkeys();
2582 packet_start(success ?
2583 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2585 packet_write_wait();
2592 client_session2_setup(int id, int want_tty, int want_subsystem,
2593 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2598 debug2("%s: id %d", __func__, id);
2600 if ((c = channel_lookup(id)) == NULL)
2601 fatal("client_session2_setup: channel %d: unknown channel", id);
2603 packet_set_interactive(want_tty,
2604 options.ip_qos_interactive, options.ip_qos_bulk);
2609 /* Store window size in the packet. */
2610 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2611 memset(&ws, 0, sizeof(ws));
2613 channel_request_start(id, "pty-req", 1);
2614 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
2615 packet_put_cstring(term != NULL ? term : "");
2616 packet_put_int((u_int)ws.ws_col);
2617 packet_put_int((u_int)ws.ws_row);
2618 packet_put_int((u_int)ws.ws_xpixel);
2619 packet_put_int((u_int)ws.ws_ypixel);
2621 tiop = get_saved_tio();
2622 tty_make_modes(-1, tiop);
2624 /* XXX wait for reply */
2628 /* Transfer any environment variables from client to server */
2629 if (options.num_send_env != 0 && env != NULL) {
2633 debug("Sending environment.");
2634 for (i = 0; env[i] != NULL; i++) {
2636 name = xstrdup(env[i]);
2637 if ((val = strchr(name, '=')) == NULL) {
2644 for (j = 0; j < options.num_send_env; j++) {
2645 if (match_pattern(name, options.send_env[j])) {
2651 debug3("Ignored env %s", name);
2656 debug("Sending env %s = %s", name, val);
2657 channel_request_start(id, "env", 0);
2658 packet_put_cstring(name);
2659 packet_put_cstring(val);
2665 len = buffer_len(cmd);
2669 if (want_subsystem) {
2670 debug("Sending subsystem: %.*s",
2671 len, (u_char*)buffer_ptr(cmd));
2672 channel_request_start(id, "subsystem", 1);
2673 client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
2675 debug("Sending command: %.*s",
2676 len, (u_char*)buffer_ptr(cmd));
2677 channel_request_start(id, "exec", 1);
2678 client_expect_confirm(id, "exec", CONFIRM_CLOSE);
2680 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2683 channel_request_start(id, "shell", 1);
2684 client_expect_confirm(id, "shell", CONFIRM_CLOSE);
2690 client_init_dispatch_20(void)
2692 dispatch_init(&dispatch_protocol_error);
2694 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2695 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2696 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2697 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2698 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2699 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2700 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2701 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2702 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2703 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2704 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2705 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2708 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2710 /* global request reply messages */
2711 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2712 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2716 client_init_dispatch_13(void)
2718 dispatch_init(NULL);
2719 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2720 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2721 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2722 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2723 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2724 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2725 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2726 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2727 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2729 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2730 &client_input_agent_open : &deny_input_open);
2731 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2732 &x11_input_open : &deny_input_open);
2736 client_init_dispatch_15(void)
2738 client_init_dispatch_13();
2739 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2740 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2744 client_init_dispatch(void)
2747 client_init_dispatch_20();
2749 client_init_dispatch_13();
2751 client_init_dispatch_15();
2755 client_stop_mux(void)
2757 if (options.control_path != NULL && muxserver_sock != -1)
2758 unlink(options.control_path);
2760 * If we are in persist mode, or don't have a shell, signal that we
2761 * should close when all active channels are closed.
2763 if (options.control_persist || no_shell_flag) {
2765 setproctitle("[stopped mux]");
2769 /* client specific fatal cleanup */
2773 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2774 leave_non_blocking();
2775 if (options.control_path != NULL && muxserver_sock != -1)
2776 unlink(options.control_path);
2777 ssh_kill_proxy_command();