]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/clientloop.c
Make linux_ptrace() use linux_msg() instead of printf().
[FreeBSD/FreeBSD.git] / crypto / openssh / clientloop.c
1 /* $OpenBSD: clientloop.c,v 1.317 2018/07/11 18:53:29 markus Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * The main loop for the interactive session (client side).
7  *
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".
13  *
14  *
15  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
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.
25  *
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.
36  *
37  *
38  * SSH2 support added by Markus Friedl.
39  * Copyright (c) 1999, 2000, 2001 Markus Friedl.  All rights reserved.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
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.
49  *
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.
60  */
61
62 #include "includes.h"
63
64 #include <sys/types.h>
65 #include <sys/ioctl.h>
66 #ifdef HAVE_SYS_STAT_H
67 # include <sys/stat.h>
68 #endif
69 #ifdef HAVE_SYS_TIME_H
70 # include <sys/time.h>
71 #endif
72 #include <sys/socket.h>
73
74 #include <ctype.h>
75 #include <errno.h>
76 #ifdef HAVE_PATHS_H
77 #include <paths.h>
78 #endif
79 #include <signal.h>
80 #include <stdarg.h>
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <termios.h>
85 #include <pwd.h>
86 #include <unistd.h>
87 #include <limits.h>
88
89 #include "openbsd-compat/sys-queue.h"
90 #include "xmalloc.h"
91 #include "ssh.h"
92 #include "ssh2.h"
93 #include "packet.h"
94 #include "sshbuf.h"
95 #include "compat.h"
96 #include "channels.h"
97 #include "dispatch.h"
98 #include "sshkey.h"
99 #include "cipher.h"
100 #include "kex.h"
101 #include "myproposal.h"
102 #include "log.h"
103 #include "misc.h"
104 #include "readconf.h"
105 #include "clientloop.h"
106 #include "sshconnect.h"
107 #include "authfd.h"
108 #include "atomicio.h"
109 #include "sshpty.h"
110 #include "match.h"
111 #include "msg.h"
112 #include "ssherr.h"
113 #include "hostfile.h"
114
115 /* import options */
116 extern Options options;
117
118 /* Flag indicating that stdin should be redirected from /dev/null. */
119 extern int stdin_null_flag;
120
121 /* Flag indicating that no shell has been requested */
122 extern int no_shell_flag;
123
124 /* Flag indicating that ssh should daemonise after authentication is complete */
125 extern int fork_after_authentication_flag;
126
127 /* Control socket */
128 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
129
130 /*
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.
134  */
135 extern char *host;
136
137 /*
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.
142  */
143 static volatile sig_atomic_t received_window_change_signal = 0;
144 static volatile sig_atomic_t received_signal = 0;
145
146 /* Flag indicating whether the user's terminal is in non-blocking mode. */
147 static int in_non_blocking_mode = 0;
148
149 /* Time when backgrounded control master using ControlPersist should exit */
150 static time_t control_persist_exit_time = 0;
151
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. */
162
163 static void client_init_dispatch(void);
164 int     session_ident = -1;
165
166 /* Track escape per proto2 channel */
167 struct escape_filter_ctx {
168         int escape_pending;
169         int escape_char;
170 };
171
172 /* Context for channel confirmation replies */
173 struct channel_reply_ctx {
174         const char *request_type;
175         int id;
176         enum confirm_action action;
177 };
178
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;
184         void *ctx;
185         int ref_count;
186 };
187 TAILQ_HEAD(global_confirms, global_confirm);
188 static struct global_confirms global_confirms =
189     TAILQ_HEAD_INITIALIZER(global_confirms);
190
191 void ssh_process_session2_setup(int, int, int, struct sshbuf *);
192
193 /* Restores stdin to blocking mode. */
194
195 static void
196 leave_non_blocking(void)
197 {
198         if (in_non_blocking_mode) {
199                 unset_nonblock(fileno(stdin));
200                 in_non_blocking_mode = 0;
201         }
202 }
203
204 /*
205  * Signal handler for the window change signal (SIGWINCH).  This just sets a
206  * flag indicating that the window has changed.
207  */
208 /*ARGSUSED */
209 static void
210 window_change_handler(int sig)
211 {
212         received_window_change_signal = 1;
213 }
214
215 /*
216  * Signal handler for signals that cause the program to terminate.  These
217  * signals must be trapped to restore terminal modes.
218  */
219 /*ARGSUSED */
220 static void
221 signal_handler(int sig)
222 {
223         received_signal = sig;
224         quit_pending = 1;
225 }
226
227 /*
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.
232  */
233 static void
234 set_control_persist_exit_time(struct ssh *ssh)
235 {
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);
251         }
252         /* else we are already counting down to the timeout */
253 }
254
255 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
256 static int
257 client_x11_display_valid(const char *display)
258 {
259         size_t i, dlen;
260
261         if (display == NULL)
262                 return 0;
263
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]);
269                         return 0;
270                 }
271         }
272         return 1;
273 }
274
275 #define SSH_X11_PROTO           "MIT-MAGIC-COOKIE-1"
276 #define X11_TIMEOUT_SLACK       60
277 int
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)
281 {
282         char cmd[1024], line[512], xdisplay[512];
283         char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
284         static char proto[512], data[512];
285         FILE *f;
286         int got_data = 0, generated = 0, do_unlink = 0, r;
287         struct stat st;
288         u_int now, x11_timeout_real;
289
290         *_proto = proto;
291         *_data = data;
292         proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
293
294         if (!client_x11_display_valid(display)) {
295                 if (display != NULL)
296                         logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
297                             display);
298                 return -1;
299         }
300         if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
301                 debug("No xauth program.");
302                 xauth_path = NULL;
303         }
304
305         if (xauth_path != NULL) {
306                 /*
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
311                  *      is not perfect.
312                  */
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__);
318                                 return -1;
319                         }
320                         display = xdisplay;
321                 }
322                 if (trusted == 0) {
323                         /*
324                          * Generate an untrusted X11 auth cookie.
325                          *
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.
329                          */
330                         mktemp_proto(xauthdir, sizeof(xauthdir));
331                         if (mkdtemp(xauthdir) == NULL) {
332                                 error("%s: mkdtemp: %s",
333                                     __func__, strerror(errno));
334                                 return -1;
335                         }
336                         do_unlink = 1;
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__);
341                                 unlink(xauthfile);
342                                 rmdir(xauthdir);
343                                 return -1;
344                         }
345
346                         if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK)
347                                 x11_timeout_real = UINT_MAX;
348                         else
349                                 x11_timeout_real = timeout + X11_TIMEOUT_SLACK;
350                         if ((r = snprintf(cmd, sizeof(cmd),
351                             "%s -f %s generate %s " SSH_X11_PROTO
352                             " untrusted timeout %u 2>" _PATH_DEVNULL,
353                             xauth_path, xauthfile, display,
354                             x11_timeout_real)) < 0 ||
355                             (size_t)r >= sizeof(cmd))
356                                 fatal("%s: cmd too long", __func__);
357                         debug2("%s: %s", __func__, cmd);
358                         if (x11_refuse_time == 0) {
359                                 now = monotime() + 1;
360                                 if (UINT_MAX - timeout < now)
361                                         x11_refuse_time = UINT_MAX;
362                                 else
363                                         x11_refuse_time = now + timeout;
364                                 channel_set_x11_refuse_time(ssh,
365                                     x11_refuse_time);
366                         }
367                         if (system(cmd) == 0)
368                                 generated = 1;
369                 }
370
371                 /*
372                  * When in untrusted mode, we read the cookie only if it was
373                  * successfully generated as an untrusted one in the step
374                  * above.
375                  */
376                 if (trusted || generated) {
377                         snprintf(cmd, sizeof(cmd),
378                             "%s %s%s list %s 2>" _PATH_DEVNULL,
379                             xauth_path,
380                             generated ? "-f " : "" ,
381                             generated ? xauthfile : "",
382                             display);
383                         debug2("x11_get_proto: %s", cmd);
384                         f = popen(cmd, "r");
385                         if (f && fgets(line, sizeof(line), f) &&
386                             sscanf(line, "%*s %511s %511s", proto, data) == 2)
387                                 got_data = 1;
388                         if (f)
389                                 pclose(f);
390                 }
391         }
392
393         if (do_unlink) {
394                 unlink(xauthfile);
395                 rmdir(xauthdir);
396         }
397
398         /* Don't fall back to fake X11 data for untrusted forwarding */
399         if (!trusted && !got_data) {
400                 error("Warning: untrusted X11 forwarding setup failed: "
401                     "xauth key data not generated");
402                 return -1;
403         }
404
405         /*
406          * If we didn't get authentication data, just make up some
407          * data.  The forwarding code will check the validity of the
408          * response anyway, and substitute this data.  The X11
409          * server, however, will ignore this fake data and use
410          * whatever authentication mechanisms it was using otherwise
411          * for the local connection.
412          */
413         if (!got_data) {
414                 u_int8_t rnd[16];
415                 u_int i;
416
417                 logit("Warning: No xauth data; "
418                     "using fake authentication data for X11 forwarding.");
419                 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
420                 arc4random_buf(rnd, sizeof(rnd));
421                 for (i = 0; i < sizeof(rnd); i++) {
422                         snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
423                             rnd[i]);
424                 }
425         }
426
427         return 0;
428 }
429
430 /*
431  * Checks if the client window has changed, and sends a packet about it to
432  * the server if so.  The actual change is detected elsewhere (by a software
433  * interrupt on Unix); this just checks the flag and sends a message if
434  * appropriate.
435  */
436
437 static void
438 client_check_window_change(struct ssh *ssh)
439 {
440         if (!received_window_change_signal)
441                 return;
442         /** XXX race */
443         received_window_change_signal = 0;
444
445         debug2("%s: changed", __func__);
446
447         channel_send_window_changes(ssh);
448 }
449
450 static int
451 client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
452 {
453         struct global_confirm *gc;
454
455         if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
456                 return 0;
457         if (gc->cb != NULL)
458                 gc->cb(ssh, type, seq, gc->ctx);
459         if (--gc->ref_count <= 0) {
460                 TAILQ_REMOVE(&global_confirms, gc, entry);
461                 explicit_bzero(gc, sizeof(*gc));
462                 free(gc);
463         }
464
465         packet_set_alive_timeouts(0);
466         return 0;
467 }
468
469 static void
470 server_alive_check(void)
471 {
472         if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
473                 logit("Timeout, server %s not responding.", host);
474                 cleanup_exit(255);
475         }
476         packet_start(SSH2_MSG_GLOBAL_REQUEST);
477         packet_put_cstring("keepalive@openssh.com");
478         packet_put_char(1);     /* boolean: want reply */
479         packet_send();
480         /* Insert an empty placeholder to maintain ordering */
481         client_register_global_confirm(NULL, NULL);
482 }
483
484 /*
485  * Waits until the client can do something (some data becomes available on
486  * one of the file descriptors).
487  */
488 static void
489 client_wait_until_can_do_something(struct ssh *ssh,
490     fd_set **readsetp, fd_set **writesetp,
491     int *maxfdp, u_int *nallocp, int rekeying)
492 {
493         struct timeval tv, *tvp;
494         int timeout_secs;
495         time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
496         int r, ret;
497
498         /* Add any selections by the channel mechanism. */
499         channel_prepare_select(active_state, readsetp, writesetp, maxfdp,
500             nallocp, &minwait_secs);
501
502         /* channel_prepare_select could have closed the last channel */
503         if (session_closed && !channel_still_open(ssh) &&
504             !packet_have_data_to_write()) {
505                 /* clear mask since we did not call select() */
506                 memset(*readsetp, 0, *nallocp);
507                 memset(*writesetp, 0, *nallocp);
508                 return;
509         }
510
511         FD_SET(connection_in, *readsetp);
512
513         /* Select server connection if have data to write to the server. */
514         if (packet_have_data_to_write())
515                 FD_SET(connection_out, *writesetp);
516
517         /*
518          * Wait for something to happen.  This will suspend the process until
519          * some selected descriptor can be read, written, or has some other
520          * event pending, or a timeout expires.
521          */
522
523         timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
524         if (options.server_alive_interval > 0) {
525                 timeout_secs = options.server_alive_interval;
526                 server_alive_time = now + options.server_alive_interval;
527         }
528         if (options.rekey_interval > 0 && !rekeying)
529                 timeout_secs = MINIMUM(timeout_secs, packet_get_rekey_timeout());
530         set_control_persist_exit_time(ssh);
531         if (control_persist_exit_time > 0) {
532                 timeout_secs = MINIMUM(timeout_secs,
533                         control_persist_exit_time - now);
534                 if (timeout_secs < 0)
535                         timeout_secs = 0;
536         }
537         if (minwait_secs != 0)
538                 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
539         if (timeout_secs == INT_MAX)
540                 tvp = NULL;
541         else {
542                 tv.tv_sec = timeout_secs;
543                 tv.tv_usec = 0;
544                 tvp = &tv;
545         }
546
547         ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
548         if (ret < 0) {
549                 /*
550                  * We have to clear the select masks, because we return.
551                  * We have to return, because the mainloop checks for the flags
552                  * set by the signal handlers.
553                  */
554                 memset(*readsetp, 0, *nallocp);
555                 memset(*writesetp, 0, *nallocp);
556
557                 if (errno == EINTR)
558                         return;
559                 /* Note: we might still have data in the buffers. */
560                 if ((r = sshbuf_putf(stderr_buffer,
561                     "select: %s\r\n", strerror(errno))) != 0)
562                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
563                 quit_pending = 1;
564         } else if (ret == 0) {
565                 /*
566                  * Timeout.  Could have been either keepalive or rekeying.
567                  * Keepalive we check here, rekeying is checked in clientloop.
568                  */
569                 if (server_alive_time != 0 && server_alive_time <= monotime())
570                         server_alive_check();
571         }
572
573 }
574
575 static void
576 client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
577 {
578         /* Flush stdout and stderr buffers. */
579         if (sshbuf_len(bout) > 0)
580                 atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
581                     sshbuf_len(bout));
582         if (sshbuf_len(berr) > 0)
583                 atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
584                     sshbuf_len(berr));
585
586         leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
587
588         sshbuf_reset(bin);
589         sshbuf_reset(bout);
590         sshbuf_reset(berr);
591
592         /* Send the suspend signal to the program itself. */
593         kill(getpid(), SIGTSTP);
594
595         /* Reset window sizes in case they have changed */
596         received_window_change_signal = 1;
597
598         enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
599 }
600
601 static void
602 client_process_net_input(fd_set *readset)
603 {
604         char buf[SSH_IOBUFSZ];
605         int r, len;
606
607         /*
608          * Read input from the server, and add any such data to the buffer of
609          * the packet subsystem.
610          */
611         if (FD_ISSET(connection_in, readset)) {
612                 /* Read as much as possible. */
613                 len = read(connection_in, buf, sizeof(buf));
614                 if (len == 0) {
615                         /*
616                          * Received EOF.  The remote host has closed the
617                          * connection.
618                          */
619                         if ((r = sshbuf_putf(stderr_buffer,
620                             "Connection to %.300s closed by remote host.\r\n",
621                             host)) != 0)
622                                 fatal("%s: buffer error: %s",
623                                     __func__, ssh_err(r));
624                         quit_pending = 1;
625                         return;
626                 }
627                 /*
628                  * There is a kernel bug on Solaris that causes select to
629                  * sometimes wake up even though there is no data available.
630                  */
631                 if (len < 0 &&
632                     (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
633                         len = 0;
634
635                 if (len < 0) {
636                         /*
637                          * An error has encountered.  Perhaps there is a
638                          * network problem.
639                          */
640                         if ((r = sshbuf_putf(stderr_buffer,
641                             "Read from remote host %.300s: %.100s\r\n",
642                             host, strerror(errno))) != 0)
643                                 fatal("%s: buffer error: %s",
644                                     __func__, ssh_err(r));
645                         quit_pending = 1;
646                         return;
647                 }
648                 packet_process_incoming(buf, len);
649         }
650 }
651
652 static void
653 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
654 {
655         struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
656         char errmsg[256];
657         int r, tochan;
658
659         /*
660          * If a TTY was explicitly requested, then a failure to allocate
661          * one is fatal.
662          */
663         if (cr->action == CONFIRM_TTY &&
664             (options.request_tty == REQUEST_TTY_FORCE ||
665             options.request_tty == REQUEST_TTY_YES))
666                 cr->action = CONFIRM_CLOSE;
667
668         /* XXX suppress on mux _client_ quietmode */
669         tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
670             c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
671
672         if (type == SSH2_MSG_CHANNEL_SUCCESS) {
673                 debug2("%s request accepted on channel %d",
674                     cr->request_type, c->self);
675         } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
676                 if (tochan) {
677                         snprintf(errmsg, sizeof(errmsg),
678                             "%s request failed\r\n", cr->request_type);
679                 } else {
680                         snprintf(errmsg, sizeof(errmsg),
681                             "%s request failed on channel %d",
682                             cr->request_type, c->self);
683                 }
684                 /* If error occurred on primary session channel, then exit */
685                 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
686                         fatal("%s", errmsg);
687                 /*
688                  * If error occurred on mux client, append to
689                  * their stderr.
690                  */
691                 if (tochan) {
692                         if ((r = sshbuf_put(c->extended, errmsg,
693                             strlen(errmsg))) != 0)
694                                 fatal("%s: buffer error %s", __func__,
695                                     ssh_err(r));
696                 } else
697                         error("%s", errmsg);
698                 if (cr->action == CONFIRM_TTY) {
699                         /*
700                          * If a TTY allocation error occurred, then arrange
701                          * for the correct TTY to leave raw mode.
702                          */
703                         if (c->self == session_ident)
704                                 leave_raw_mode(0);
705                         else
706                                 mux_tty_alloc_failed(ssh, c);
707                 } else if (cr->action == CONFIRM_CLOSE) {
708                         chan_read_failed(ssh, c);
709                         chan_write_failed(ssh, c);
710                 }
711         }
712         free(cr);
713 }
714
715 static void
716 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
717 {
718         free(ctx);
719 }
720
721 void
722 client_expect_confirm(struct ssh *ssh, int id, const char *request,
723     enum confirm_action action)
724 {
725         struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
726
727         cr->request_type = request;
728         cr->action = action;
729
730         channel_register_status_confirm(ssh, id, client_status_confirm,
731             client_abandon_status_confirm, cr);
732 }
733
734 void
735 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
736 {
737         struct global_confirm *gc, *last_gc;
738
739         /* Coalesce identical callbacks */
740         last_gc = TAILQ_LAST(&global_confirms, global_confirms);
741         if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
742                 if (++last_gc->ref_count >= INT_MAX)
743                         fatal("%s: last_gc->ref_count = %d",
744                             __func__, last_gc->ref_count);
745                 return;
746         }
747
748         gc = xcalloc(1, sizeof(*gc));
749         gc->cb = cb;
750         gc->ctx = ctx;
751         gc->ref_count = 1;
752         TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
753 }
754
755 static void
756 process_cmdline(struct ssh *ssh)
757 {
758         void (*handler)(int);
759         char *s, *cmd;
760         int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
761         struct Forward fwd;
762
763         memset(&fwd, 0, sizeof(fwd));
764
765         leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
766         handler = signal(SIGINT, SIG_IGN);
767         cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
768         if (s == NULL)
769                 goto out;
770         while (isspace((u_char)*s))
771                 s++;
772         if (*s == '-')
773                 s++;    /* Skip cmdline '-', if any */
774         if (*s == '\0')
775                 goto out;
776
777         if (*s == 'h' || *s == 'H' || *s == '?') {
778                 logit("Commands:");
779                 logit("      -L[bind_address:]port:host:hostport    "
780                     "Request local forward");
781                 logit("      -R[bind_address:]port:host:hostport    "
782                     "Request remote forward");
783                 logit("      -D[bind_address:]port                  "
784                     "Request dynamic forward");
785                 logit("      -KL[bind_address:]port                 "
786                     "Cancel local forward");
787                 logit("      -KR[bind_address:]port                 "
788                     "Cancel remote forward");
789                 logit("      -KD[bind_address:]port                 "
790                     "Cancel dynamic forward");
791                 if (!options.permit_local_command)
792                         goto out;
793                 logit("      !args                                  "
794                     "Execute local command");
795                 goto out;
796         }
797
798         if (*s == '!' && options.permit_local_command) {
799                 s++;
800                 ssh_local_cmd(s);
801                 goto out;
802         }
803
804         if (*s == 'K') {
805                 delete = 1;
806                 s++;
807         }
808         if (*s == 'L')
809                 local = 1;
810         else if (*s == 'R')
811                 remote = 1;
812         else if (*s == 'D')
813                 dynamic = 1;
814         else {
815                 logit("Invalid command.");
816                 goto out;
817         }
818
819         while (isspace((u_char)*++s))
820                 ;
821
822         /* XXX update list of forwards in options */
823         if (delete) {
824                 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
825                 if (!parse_forward(&fwd, s, 1, 0)) {
826                         logit("Bad forwarding close specification.");
827                         goto out;
828                 }
829                 if (remote)
830                         ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
831                 else if (dynamic)
832                         ok = channel_cancel_lport_listener(ssh, &fwd,
833                             0, &options.fwd_opts) > 0;
834                 else
835                         ok = channel_cancel_lport_listener(ssh, &fwd,
836                             CHANNEL_CANCEL_PORT_STATIC,
837                             &options.fwd_opts) > 0;
838                 if (!ok) {
839                         logit("Unknown port forwarding.");
840                         goto out;
841                 }
842                 logit("Canceled forwarding.");
843         } else {
844                 if (!parse_forward(&fwd, s, dynamic, remote)) {
845                         logit("Bad forwarding specification.");
846                         goto out;
847                 }
848                 if (local || dynamic) {
849                         if (!channel_setup_local_fwd_listener(ssh, &fwd,
850                             &options.fwd_opts)) {
851                                 logit("Port forwarding failed.");
852                                 goto out;
853                         }
854                 } else {
855                         if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
856                                 logit("Port forwarding failed.");
857                                 goto out;
858                         }
859                 }
860                 logit("Forwarding port.");
861         }
862
863 out:
864         signal(SIGINT, handler);
865         enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
866         free(cmd);
867         free(fwd.listen_host);
868         free(fwd.listen_path);
869         free(fwd.connect_host);
870         free(fwd.connect_path);
871 }
872
873 /* reasons to suppress output of an escape command in help output */
874 #define SUPPRESS_NEVER          0       /* never suppress, always show */
875 #define SUPPRESS_MUXCLIENT      1       /* don't show in mux client sessions */
876 #define SUPPRESS_MUXMASTER      2       /* don't show in mux master sessions */
877 #define SUPPRESS_SYSLOG         4       /* don't show when logging to syslog */
878 struct escape_help_text {
879         const char *cmd;
880         const char *text;
881         unsigned int flags;
882 };
883 static struct escape_help_text esc_txt[] = {
884     {".",  "terminate session", SUPPRESS_MUXMASTER},
885     {".",  "terminate connection (and any multiplexed sessions)",
886         SUPPRESS_MUXCLIENT},
887     {"B",  "send a BREAK to the remote system", SUPPRESS_NEVER},
888     {"C",  "open a command line", SUPPRESS_MUXCLIENT},
889     {"R",  "request rekey", SUPPRESS_NEVER},
890     {"V/v",  "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
891     {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
892     {"#",  "list forwarded connections", SUPPRESS_NEVER},
893     {"&",  "background ssh (when waiting for connections to terminate)",
894         SUPPRESS_MUXCLIENT},
895     {"?", "this message", SUPPRESS_NEVER},
896 };
897
898 static void
899 print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
900     int using_stderr)
901 {
902         unsigned int i, suppress_flags;
903         int r;
904
905         if ((r = sshbuf_putf(b,
906             "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
907                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
908
909         suppress_flags =
910             (mux_client ? SUPPRESS_MUXCLIENT : 0) |
911             (mux_client ? 0 : SUPPRESS_MUXMASTER) |
912             (using_stderr ? 0 : SUPPRESS_SYSLOG);
913
914         for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
915                 if (esc_txt[i].flags & suppress_flags)
916                         continue;
917                 if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
918                     escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
919                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
920         }
921
922         if ((r = sshbuf_putf(b,
923             " %c%c   - send the escape character by typing it twice\r\n"
924             "(Note that escapes are only recognized immediately after "
925             "newline.)\r\n", escape_char, escape_char)) != 0)
926                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
927 }
928
929 /*
930  * Process the characters one by one.
931  */
932 static int
933 process_escapes(struct ssh *ssh, Channel *c,
934     struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
935     char *buf, int len)
936 {
937         pid_t pid;
938         int r, bytes = 0;
939         u_int i;
940         u_char ch;
941         char *s;
942         struct escape_filter_ctx *efc = c->filter_ctx == NULL ?
943             NULL : (struct escape_filter_ctx *)c->filter_ctx;
944
945         if (c->filter_ctx == NULL)
946                 return 0;
947
948         if (len <= 0)
949                 return (0);
950
951         for (i = 0; i < (u_int)len; i++) {
952                 /* Get one character at a time. */
953                 ch = buf[i];
954
955                 if (efc->escape_pending) {
956                         /* We have previously seen an escape character. */
957                         /* Clear the flag now. */
958                         efc->escape_pending = 0;
959
960                         /* Process the escaped character. */
961                         switch (ch) {
962                         case '.':
963                                 /* Terminate the connection. */
964                                 if ((r = sshbuf_putf(berr, "%c.\r\n",
965                                     efc->escape_char)) != 0)
966                                         fatal("%s: buffer error: %s",
967                                             __func__, ssh_err(r));
968                                 if (c && c->ctl_chan != -1) {
969                                         chan_read_failed(ssh, c);
970                                         chan_write_failed(ssh, c);
971                                         if (c->detach_user) {
972                                                 c->detach_user(ssh,
973                                                     c->self, NULL);
974                                         }
975                                         c->type = SSH_CHANNEL_ABANDONED;
976                                         sshbuf_reset(c->input);
977                                         chan_ibuf_empty(ssh, c);
978                                         return 0;
979                                 } else
980                                         quit_pending = 1;
981                                 return -1;
982
983                         case 'Z' - 64:
984                                 /* XXX support this for mux clients */
985                                 if (c && c->ctl_chan != -1) {
986                                         char b[16];
987  noescape:
988                                         if (ch == 'Z' - 64)
989                                                 snprintf(b, sizeof b, "^Z");
990                                         else
991                                                 snprintf(b, sizeof b, "%c", ch);
992                                         if ((r = sshbuf_putf(berr,
993                                             "%c%s escape not available to "
994                                             "multiplexed sessions\r\n",
995                                             efc->escape_char, b)) != 0)
996                                                 fatal("%s: buffer error: %s",
997                                                     __func__, ssh_err(r));
998                                         continue;
999                                 }
1000                                 /* Suspend the program. Inform the user */
1001                                 if ((r = sshbuf_putf(berr,
1002                                     "%c^Z [suspend ssh]\r\n",
1003                                     efc->escape_char)) != 0)
1004                                         fatal("%s: buffer error: %s",
1005                                             __func__, ssh_err(r));
1006
1007                                 /* Restore terminal modes and suspend. */
1008                                 client_suspend_self(bin, bout, berr);
1009
1010                                 /* We have been continued. */
1011                                 continue;
1012
1013                         case 'B':
1014                                 if ((r = sshbuf_putf(berr,
1015                                     "%cB\r\n", efc->escape_char)) != 0)
1016                                         fatal("%s: buffer error: %s",
1017                                             __func__, ssh_err(r));
1018                                 channel_request_start(ssh, c->self, "break", 0);
1019                                 if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
1020                                     (r = sshpkt_send(ssh)) != 0)
1021                                         fatal("%s: %s", __func__,
1022                                             ssh_err(r));
1023                                 continue;
1024
1025                         case 'R':
1026                                 if (datafellows & SSH_BUG_NOREKEY)
1027                                         logit("Server does not "
1028                                             "support re-keying");
1029                                 else
1030                                         need_rekeying = 1;
1031                                 continue;
1032
1033                         case 'V':
1034                                 /* FALLTHROUGH */
1035                         case 'v':
1036                                 if (c && c->ctl_chan != -1)
1037                                         goto noescape;
1038                                 if (!log_is_on_stderr()) {
1039                                         if ((r = sshbuf_putf(berr,
1040                                             "%c%c [Logging to syslog]\r\n",
1041                                             efc->escape_char, ch)) != 0)
1042                                                 fatal("%s: buffer error: %s",
1043                                                     __func__, ssh_err(r));
1044                                         continue;
1045                                 }
1046                                 if (ch == 'V' && options.log_level >
1047                                     SYSLOG_LEVEL_QUIET)
1048                                         log_change_level(--options.log_level);
1049                                 if (ch == 'v' && options.log_level <
1050                                     SYSLOG_LEVEL_DEBUG3)
1051                                         log_change_level(++options.log_level);
1052                                 if ((r = sshbuf_putf(berr,
1053                                     "%c%c [LogLevel %s]\r\n",
1054                                     efc->escape_char, ch,
1055                                     log_level_name(options.log_level))) != 0)
1056                                         fatal("%s: buffer error: %s",
1057                                             __func__, ssh_err(r));
1058                                 continue;
1059
1060                         case '&':
1061                                 if (c && c->ctl_chan != -1)
1062                                         goto noescape;
1063                                 /*
1064                                  * Detach the program (continue to serve
1065                                  * connections, but put in background and no
1066                                  * more new connections).
1067                                  */
1068                                 /* Restore tty modes. */
1069                                 leave_raw_mode(
1070                                     options.request_tty == REQUEST_TTY_FORCE);
1071
1072                                 /* Stop listening for new connections. */
1073                                 channel_stop_listening(ssh);
1074
1075                                 if ((r = sshbuf_putf(berr,
1076                                     "%c& [backgrounded]\n", efc->escape_char))
1077                                      != 0)
1078                                         fatal("%s: buffer error: %s",
1079                                             __func__, ssh_err(r));
1080
1081                                 /* Fork into background. */
1082                                 pid = fork();
1083                                 if (pid < 0) {
1084                                         error("fork: %.100s", strerror(errno));
1085                                         continue;
1086                                 }
1087                                 if (pid != 0) { /* This is the parent. */
1088                                         /* The parent just exits. */
1089                                         exit(0);
1090                                 }
1091                                 /* The child continues serving connections. */
1092                                 /* fake EOF on stdin */
1093                                 if ((r = sshbuf_put_u8(bin, 4)) != 0)
1094                                         fatal("%s: buffer error: %s",
1095                                             __func__, ssh_err(r));
1096                                 return -1;
1097                         case '?':
1098                                 print_escape_help(berr, efc->escape_char,
1099                                     (c && c->ctl_chan != -1),
1100                                     log_is_on_stderr());
1101                                 continue;
1102
1103                         case '#':
1104                                 if ((r = sshbuf_putf(berr, "%c#\r\n",
1105                                     efc->escape_char)) != 0)
1106                                         fatal("%s: buffer error: %s",
1107                                             __func__, ssh_err(r));
1108                                 s = channel_open_message(ssh);
1109                                 if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1110                                         fatal("%s: buffer error: %s",
1111                                             __func__, ssh_err(r));
1112                                 free(s);
1113                                 continue;
1114
1115                         case 'C':
1116                                 if (c && c->ctl_chan != -1)
1117                                         goto noescape;
1118                                 process_cmdline(ssh);
1119                                 continue;
1120
1121                         default:
1122                                 if (ch != efc->escape_char) {
1123                                         if ((r = sshbuf_put_u8(bin,
1124                                             efc->escape_char)) != 0)
1125                                                 fatal("%s: buffer error: %s",
1126                                                     __func__, ssh_err(r));
1127                                         bytes++;
1128                                 }
1129                                 /* Escaped characters fall through here */
1130                                 break;
1131                         }
1132                 } else {
1133                         /*
1134                          * The previous character was not an escape char.
1135                          * Check if this is an escape.
1136                          */
1137                         if (last_was_cr && ch == efc->escape_char) {
1138                                 /*
1139                                  * It is. Set the flag and continue to
1140                                  * next character.
1141                                  */
1142                                 efc->escape_pending = 1;
1143                                 continue;
1144                         }
1145                 }
1146
1147                 /*
1148                  * Normal character.  Record whether it was a newline,
1149                  * and append it to the buffer.
1150                  */
1151                 last_was_cr = (ch == '\r' || ch == '\n');
1152                 if ((r = sshbuf_put_u8(bin, ch)) != 0)
1153                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
1154                 bytes++;
1155         }
1156         return bytes;
1157 }
1158
1159 /*
1160  * Get packets from the connection input buffer, and process them as long as
1161  * there are packets available.
1162  *
1163  * Any unknown packets received during the actual
1164  * session cause the session to terminate.  This is
1165  * intended to make debugging easier since no
1166  * confirmations are sent.  Any compatible protocol
1167  * extensions must be negotiated during the
1168  * preparatory phase.
1169  */
1170
1171 static void
1172 client_process_buffered_input_packets(void)
1173 {
1174         ssh_dispatch_run_fatal(active_state, DISPATCH_NONBLOCK, &quit_pending);
1175 }
1176
1177 /* scan buf[] for '~' before sending data to the peer */
1178
1179 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1180 void *
1181 client_new_escape_filter_ctx(int escape_char)
1182 {
1183         struct escape_filter_ctx *ret;
1184
1185         ret = xcalloc(1, sizeof(*ret));
1186         ret->escape_pending = 0;
1187         ret->escape_char = escape_char;
1188         return (void *)ret;
1189 }
1190
1191 /* Free the escape filter context on channel free */
1192 void
1193 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1194 {
1195         free(ctx);
1196 }
1197
1198 int
1199 client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1200 {
1201         if (c->extended_usage != CHAN_EXTENDED_WRITE)
1202                 return 0;
1203
1204         return process_escapes(ssh, c, c->input, c->output, c->extended,
1205             buf, len);
1206 }
1207
1208 static void
1209 client_channel_closed(struct ssh *ssh, int id, void *arg)
1210 {
1211         channel_cancel_cleanup(ssh, id);
1212         session_closed = 1;
1213         leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1214 }
1215
1216 /*
1217  * Implements the interactive session with the server.  This is called after
1218  * the user has been authenticated, and a command has been started on the
1219  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1220  * used as an escape character for terminating or suspending the session.
1221  */
1222 int
1223 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1224     int ssh2_chan_id)
1225 {
1226         fd_set *readset = NULL, *writeset = NULL;
1227         double start_time, total_time;
1228         int r, max_fd = 0, max_fd2 = 0, len;
1229         u_int64_t ibytes, obytes;
1230         u_int nalloc = 0;
1231         char buf[100];
1232
1233         debug("Entering interactive session.");
1234
1235         if (options.control_master &&
1236             !option_clear_or_none(options.control_path)) {
1237                 debug("pledge: id");
1238                 if (pledge("stdio rpath wpath cpath unix inet dns recvfd proc exec id tty",
1239                     NULL) == -1)
1240                         fatal("%s pledge(): %s", __func__, strerror(errno));
1241
1242         } else if (options.forward_x11 || options.permit_local_command) {
1243                 debug("pledge: exec");
1244                 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1245                     NULL) == -1)
1246                         fatal("%s pledge(): %s", __func__, strerror(errno));
1247
1248         } else if (options.update_hostkeys) {
1249                 debug("pledge: filesystem full");
1250                 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1251                     NULL) == -1)
1252                         fatal("%s pledge(): %s", __func__, strerror(errno));
1253
1254         } else if (!option_clear_or_none(options.proxy_command) ||
1255             fork_after_authentication_flag) {
1256                 debug("pledge: proc");
1257                 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1258                         fatal("%s pledge(): %s", __func__, strerror(errno));
1259
1260         } else {
1261                 debug("pledge: network");
1262                 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1263                         fatal("%s pledge(): %s", __func__, strerror(errno));
1264         }
1265
1266         start_time = monotime_double();
1267
1268         /* Initialize variables. */
1269         last_was_cr = 1;
1270         exit_status = -1;
1271         connection_in = packet_get_connection_in();
1272         connection_out = packet_get_connection_out();
1273         max_fd = MAXIMUM(connection_in, connection_out);
1274
1275         quit_pending = 0;
1276
1277         /* Initialize buffer. */
1278         if ((stderr_buffer = sshbuf_new()) == NULL)
1279                 fatal("%s: sshbuf_new failed", __func__);
1280
1281         client_init_dispatch();
1282
1283         /*
1284          * Set signal handlers, (e.g. to restore non-blocking mode)
1285          * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1286          */
1287         if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1288                 signal(SIGHUP, signal_handler);
1289         if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1290                 signal(SIGINT, signal_handler);
1291         if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1292                 signal(SIGQUIT, signal_handler);
1293         if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1294                 signal(SIGTERM, signal_handler);
1295         signal(SIGWINCH, window_change_handler);
1296
1297         if (have_pty)
1298                 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1299
1300         session_ident = ssh2_chan_id;
1301         if (session_ident != -1) {
1302                 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1303                         channel_register_filter(ssh, session_ident,
1304                             client_simple_escape_filter, NULL,
1305                             client_filter_cleanup,
1306                             client_new_escape_filter_ctx(
1307                             escape_char_arg));
1308                 }
1309                 channel_register_cleanup(ssh, session_ident,
1310                     client_channel_closed, 0);
1311         }
1312
1313         /* Main loop of the client for the interactive session mode. */
1314         while (!quit_pending) {
1315
1316                 /* Process buffered packets sent by the server. */
1317                 client_process_buffered_input_packets();
1318
1319                 if (session_closed && !channel_still_open(ssh))
1320                         break;
1321
1322                 if (ssh_packet_is_rekeying(ssh)) {
1323                         debug("rekeying in progress");
1324                 } else if (need_rekeying) {
1325                         /* manual rekey request */
1326                         debug("need rekeying");
1327                         if ((r = kex_start_rekex(ssh)) != 0)
1328                                 fatal("%s: kex_start_rekex: %s", __func__,
1329                                     ssh_err(r));
1330                         need_rekeying = 0;
1331                 } else {
1332                         /*
1333                          * Make packets from buffered channel data, and
1334                          * enqueue them for sending to the server.
1335                          */
1336                         if (packet_not_very_much_data_to_write())
1337                                 channel_output_poll(ssh);
1338
1339                         /*
1340                          * Check if the window size has changed, and buffer a
1341                          * message about it to the server if so.
1342                          */
1343                         client_check_window_change(ssh);
1344
1345                         if (quit_pending)
1346                                 break;
1347                 }
1348                 /*
1349                  * Wait until we have something to do (something becomes
1350                  * available on one of the descriptors).
1351                  */
1352                 max_fd2 = max_fd;
1353                 client_wait_until_can_do_something(ssh, &readset, &writeset,
1354                     &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh));
1355
1356                 if (quit_pending)
1357                         break;
1358
1359                 /* Do channel operations unless rekeying in progress. */
1360                 if (!ssh_packet_is_rekeying(ssh))
1361                         channel_after_select(ssh, readset, writeset);
1362
1363                 /* Buffer input from the connection.  */
1364                 client_process_net_input(readset);
1365
1366                 if (quit_pending)
1367                         break;
1368
1369                 /*
1370                  * Send as much buffered packet data as possible to the
1371                  * sender.
1372                  */
1373                 if (FD_ISSET(connection_out, writeset))
1374                         packet_write_poll();
1375
1376                 /*
1377                  * If we are a backgrounded control master, and the
1378                  * timeout has expired without any active client
1379                  * connections, then quit.
1380                  */
1381                 if (control_persist_exit_time > 0) {
1382                         if (monotime() >= control_persist_exit_time) {
1383                                 debug("ControlPersist timeout expired");
1384                                 break;
1385                         }
1386                 }
1387         }
1388         free(readset);
1389         free(writeset);
1390
1391         /* Terminate the session. */
1392
1393         /* Stop watching for window change. */
1394         signal(SIGWINCH, SIG_DFL);
1395
1396         packet_start(SSH2_MSG_DISCONNECT);
1397         packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1398         packet_put_cstring("disconnected by user");
1399         packet_put_cstring(""); /* language tag */
1400         packet_send();
1401         packet_write_wait();
1402
1403         channel_free_all(ssh);
1404
1405         if (have_pty)
1406                 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1407
1408         /* restore blocking io */
1409         if (!isatty(fileno(stdin)))
1410                 unset_nonblock(fileno(stdin));
1411         if (!isatty(fileno(stdout)))
1412                 unset_nonblock(fileno(stdout));
1413         if (!isatty(fileno(stderr)))
1414                 unset_nonblock(fileno(stderr));
1415
1416         /*
1417          * If there was no shell or command requested, there will be no remote
1418          * exit status to be returned.  In that case, clear error code if the
1419          * connection was deliberately terminated at this end.
1420          */
1421         if (no_shell_flag && received_signal == SIGTERM) {
1422                 received_signal = 0;
1423                 exit_status = 0;
1424         }
1425
1426         if (received_signal) {
1427                 verbose("Killed by signal %d.", (int) received_signal);
1428                 cleanup_exit(0);
1429         }
1430
1431         /*
1432          * In interactive mode (with pseudo tty) display a message indicating
1433          * that the connection has been closed.
1434          */
1435         if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1436                 if ((r = sshbuf_putf(stderr_buffer,
1437                     "Connection to %.64s closed.\r\n", host)) != 0)
1438                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
1439         }
1440
1441         /* Output any buffered data for stderr. */
1442         if (sshbuf_len(stderr_buffer) > 0) {
1443                 len = atomicio(vwrite, fileno(stderr),
1444                     (u_char *)sshbuf_ptr(stderr_buffer),
1445                     sshbuf_len(stderr_buffer));
1446                 if (len < 0 || (u_int)len != sshbuf_len(stderr_buffer))
1447                         error("Write failed flushing stderr buffer.");
1448                 else if ((r = sshbuf_consume(stderr_buffer, len)) != 0)
1449                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
1450         }
1451
1452         /* Clear and free any buffers. */
1453         explicit_bzero(buf, sizeof(buf));
1454         sshbuf_free(stderr_buffer);
1455
1456         /* Report bytes transferred, and transfer rates. */
1457         total_time = monotime_double() - start_time;
1458         packet_get_bytes(&ibytes, &obytes);
1459         verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1460             (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1461         if (total_time > 0)
1462                 verbose("Bytes per second: sent %.1f, received %.1f",
1463                     obytes / total_time, ibytes / total_time);
1464         /* Return the exit status of the program. */
1465         debug("Exit status %d", exit_status);
1466         return exit_status;
1467 }
1468
1469 /*********/
1470
1471 static Channel *
1472 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1473     int rchan, u_int rwindow, u_int rmaxpack)
1474 {
1475         Channel *c = NULL;
1476         struct sshbuf *b = NULL;
1477         char *listen_address, *originator_address;
1478         u_short listen_port, originator_port;
1479         int r;
1480
1481         /* Get rest of the packet */
1482         listen_address = packet_get_string(NULL);
1483         listen_port = packet_get_int();
1484         originator_address = packet_get_string(NULL);
1485         originator_port = packet_get_int();
1486         packet_check_eom();
1487
1488         debug("%s: listen %s port %d, originator %s port %d", __func__,
1489             listen_address, listen_port, originator_address, originator_port);
1490
1491         c = channel_connect_by_listen_address(ssh, listen_address, listen_port,
1492             "forwarded-tcpip", originator_address);
1493
1494         if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1495                 if ((b = sshbuf_new()) == NULL) {
1496                         error("%s: alloc reply", __func__);
1497                         goto out;
1498                 }
1499                 /* reconstruct and send to muxclient */
1500                 if ((r = sshbuf_put_u8(b, 0)) != 0 ||   /* padlen */
1501                     (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1502                     (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1503                     (r = sshbuf_put_u32(b, rchan)) != 0 ||
1504                     (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1505                     (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1506                     (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1507                     (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1508                     (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1509                     (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1510                     (r = sshbuf_put_stringb(c->output, b)) != 0) {
1511                         error("%s: compose for muxclient %s", __func__,
1512                             ssh_err(r));
1513                         goto out;
1514                 }
1515         }
1516
1517  out:
1518         sshbuf_free(b);
1519         free(originator_address);
1520         free(listen_address);
1521         return c;
1522 }
1523
1524 static Channel *
1525 client_request_forwarded_streamlocal(struct ssh *ssh,
1526     const char *request_type, int rchan)
1527 {
1528         Channel *c = NULL;
1529         char *listen_path;
1530
1531         /* Get the remote path. */
1532         listen_path = packet_get_string(NULL);
1533         /* XXX: Skip reserved field for now. */
1534         if (packet_get_string_ptr(NULL) == NULL)
1535                 fatal("%s: packet_get_string_ptr failed", __func__);
1536         packet_check_eom();
1537
1538         debug("%s: %s", __func__, listen_path);
1539
1540         c = channel_connect_by_listen_path(ssh, listen_path,
1541             "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1542         free(listen_path);
1543         return c;
1544 }
1545
1546 static Channel *
1547 client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1548 {
1549         Channel *c = NULL;
1550         char *originator;
1551         u_short originator_port;
1552         int sock;
1553
1554         if (!options.forward_x11) {
1555                 error("Warning: ssh server tried X11 forwarding.");
1556                 error("Warning: this is probably a break-in attempt by a "
1557                     "malicious server.");
1558                 return NULL;
1559         }
1560         if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1561                 verbose("Rejected X11 connection after ForwardX11Timeout "
1562                     "expired");
1563                 return NULL;
1564         }
1565         originator = packet_get_string(NULL);
1566         originator_port = packet_get_int();
1567         packet_check_eom();
1568         /* XXX check permission */
1569         debug("client_request_x11: request from %s %d", originator,
1570             originator_port);
1571         free(originator);
1572         sock = x11_connect_display(ssh);
1573         if (sock < 0)
1574                 return NULL;
1575         c = channel_new(ssh, "x11",
1576             SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1577             CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1578         c->force_drain = 1;
1579         return c;
1580 }
1581
1582 static Channel *
1583 client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1584 {
1585         Channel *c = NULL;
1586         int r, sock;
1587
1588         if (!options.forward_agent) {
1589                 error("Warning: ssh server tried agent forwarding.");
1590                 error("Warning: this is probably a break-in attempt by a "
1591                     "malicious server.");
1592                 return NULL;
1593         }
1594         if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1595                 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1596                         debug("%s: ssh_get_authentication_socket: %s",
1597                             __func__, ssh_err(r));
1598                 return NULL;
1599         }
1600         c = channel_new(ssh, "authentication agent connection",
1601             SSH_CHANNEL_OPEN, sock, sock, -1,
1602             CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1603             "authentication agent connection", 1);
1604         c->force_drain = 1;
1605         return c;
1606 }
1607
1608 char *
1609 client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1610     int local_tun, int remote_tun)
1611 {
1612         Channel *c;
1613         int fd;
1614         char *ifname = NULL;
1615
1616         if (tun_mode == SSH_TUNMODE_NO)
1617                 return 0;
1618
1619         debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1620
1621         /* Open local tunnel device */
1622         if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1623                 error("Tunnel device open failed.");
1624                 return NULL;
1625         }
1626         debug("Tunnel forwarding using interface %s", ifname);
1627
1628         c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1629             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1630         c->datagram = 1;
1631
1632 #if defined(SSH_TUN_FILTER)
1633         if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1634                 channel_register_filter(ssh, c->self, sys_tun_infilter,
1635                     sys_tun_outfilter, NULL, NULL);
1636 #endif
1637
1638         packet_start(SSH2_MSG_CHANNEL_OPEN);
1639         packet_put_cstring("tun@openssh.com");
1640         packet_put_int(c->self);
1641         packet_put_int(c->local_window_max);
1642         packet_put_int(c->local_maxpacket);
1643         packet_put_int(tun_mode);
1644         packet_put_int(remote_tun);
1645         packet_send();
1646
1647         return ifname;
1648 }
1649
1650 /* XXXX move to generic input handler */
1651 static int
1652 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1653 {
1654         Channel *c = NULL;
1655         char *ctype;
1656         int rchan;
1657         u_int rmaxpack, rwindow, len;
1658
1659         ctype = packet_get_string(&len);
1660         rchan = packet_get_int();
1661         rwindow = packet_get_int();
1662         rmaxpack = packet_get_int();
1663
1664         debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1665             ctype, rchan, rwindow, rmaxpack);
1666
1667         if (strcmp(ctype, "forwarded-tcpip") == 0) {
1668                 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1669                     rmaxpack);
1670         } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1671                 c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1672         } else if (strcmp(ctype, "x11") == 0) {
1673                 c = client_request_x11(ssh, ctype, rchan);
1674         } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1675                 c = client_request_agent(ssh, ctype, rchan);
1676         }
1677         if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1678                 debug3("proxied to downstream: %s", ctype);
1679         } else if (c != NULL) {
1680                 debug("confirm %s", ctype);
1681                 c->remote_id = rchan;
1682                 c->have_remote_id = 1;
1683                 c->remote_window = rwindow;
1684                 c->remote_maxpacket = rmaxpack;
1685                 if (c->type != SSH_CHANNEL_CONNECTING) {
1686                         packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1687                         packet_put_int(c->remote_id);
1688                         packet_put_int(c->self);
1689                         packet_put_int(c->local_window);
1690                         packet_put_int(c->local_maxpacket);
1691                         packet_send();
1692                 }
1693         } else {
1694                 debug("failure %s", ctype);
1695                 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1696                 packet_put_int(rchan);
1697                 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1698                 packet_put_cstring("open failed");
1699                 packet_put_cstring("");
1700                 packet_send();
1701         }
1702         free(ctype);
1703         return 0;
1704 }
1705
1706 static int
1707 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1708 {
1709         Channel *c = NULL;
1710         int exitval, id, reply, success = 0;
1711         char *rtype;
1712
1713         id = packet_get_int();
1714         c = channel_lookup(ssh, id);
1715         if (channel_proxy_upstream(c, type, seq, ssh))
1716                 return 0;
1717         rtype = packet_get_string(NULL);
1718         reply = packet_get_char();
1719
1720         debug("client_input_channel_req: channel %d rtype %s reply %d",
1721             id, rtype, reply);
1722
1723         if (id == -1) {
1724                 error("client_input_channel_req: request for channel -1");
1725         } else if (c == NULL) {
1726                 error("client_input_channel_req: channel %d: "
1727                     "unknown channel", id);
1728         } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1729                 packet_check_eom();
1730                 chan_rcvd_eow(ssh, c);
1731         } else if (strcmp(rtype, "exit-status") == 0) {
1732                 exitval = packet_get_int();
1733                 if (c->ctl_chan != -1) {
1734                         mux_exit_message(ssh, c, exitval);
1735                         success = 1;
1736                 } else if (id == session_ident) {
1737                         /* Record exit value of local session */
1738                         success = 1;
1739                         exit_status = exitval;
1740                 } else {
1741                         /* Probably for a mux channel that has already closed */
1742                         debug("%s: no sink for exit-status on channel %d",
1743                             __func__, id);
1744                 }
1745                 packet_check_eom();
1746         }
1747         if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1748                 if (!c->have_remote_id)
1749                         fatal("%s: channel %d: no remote_id",
1750                             __func__, c->self);
1751                 packet_start(success ?
1752                     SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1753                 packet_put_int(c->remote_id);
1754                 packet_send();
1755         }
1756         free(rtype);
1757         return 0;
1758 }
1759
1760 struct hostkeys_update_ctx {
1761         /* The hostname and (optionally) IP address string for the server */
1762         char *host_str, *ip_str;
1763
1764         /*
1765          * Keys received from the server and a flag for each indicating
1766          * whether they already exist in known_hosts.
1767          * keys_seen is filled in by hostkeys_find() and later (for new
1768          * keys) by client_global_hostkeys_private_confirm().
1769          */
1770         struct sshkey **keys;
1771         int *keys_seen;
1772         size_t nkeys, nnew;
1773
1774         /*
1775          * Keys that are in known_hosts, but were not present in the update
1776          * from the server (i.e. scheduled to be deleted).
1777          * Filled in by hostkeys_find().
1778          */
1779         struct sshkey **old_keys;
1780         size_t nold;
1781 };
1782
1783 static void
1784 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
1785 {
1786         size_t i;
1787
1788         if (ctx == NULL)
1789                 return;
1790         for (i = 0; i < ctx->nkeys; i++)
1791                 sshkey_free(ctx->keys[i]);
1792         free(ctx->keys);
1793         free(ctx->keys_seen);
1794         for (i = 0; i < ctx->nold; i++)
1795                 sshkey_free(ctx->old_keys[i]);
1796         free(ctx->old_keys);
1797         free(ctx->host_str);
1798         free(ctx->ip_str);
1799         free(ctx);
1800 }
1801
1802 static int
1803 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
1804 {
1805         struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1806         size_t i;
1807         struct sshkey **tmp;
1808
1809         if (l->status != HKF_STATUS_MATCHED || l->key == NULL)
1810                 return 0;
1811
1812         /* Mark off keys we've already seen for this host */
1813         for (i = 0; i < ctx->nkeys; i++) {
1814                 if (sshkey_equal(l->key, ctx->keys[i])) {
1815                         debug3("%s: found %s key at %s:%ld", __func__,
1816                             sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
1817                         ctx->keys_seen[i] = 1;
1818                         return 0;
1819                 }
1820         }
1821         /* This line contained a key that not offered by the server */
1822         debug3("%s: deprecated %s key at %s:%ld", __func__,
1823             sshkey_ssh_name(l->key), l->path, l->linenum);
1824         if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1825             sizeof(*ctx->old_keys))) == NULL)
1826                 fatal("%s: recallocarray failed nold = %zu",
1827                     __func__, ctx->nold);
1828         ctx->old_keys = tmp;
1829         ctx->old_keys[ctx->nold++] = l->key;
1830         l->key = NULL;
1831
1832         return 0;
1833 }
1834
1835 static void
1836 update_known_hosts(struct hostkeys_update_ctx *ctx)
1837 {
1838         int r, was_raw = 0;
1839         int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
1840             SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1841         char *fp, *response;
1842         size_t i;
1843
1844         for (i = 0; i < ctx->nkeys; i++) {
1845                 if (ctx->keys_seen[i] != 2)
1846                         continue;
1847                 if ((fp = sshkey_fingerprint(ctx->keys[i],
1848                     options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1849                         fatal("%s: sshkey_fingerprint failed", __func__);
1850                 do_log2(loglevel, "Learned new hostkey: %s %s",
1851                     sshkey_type(ctx->keys[i]), fp);
1852                 free(fp);
1853         }
1854         for (i = 0; i < ctx->nold; i++) {
1855                 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
1856                     options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1857                         fatal("%s: sshkey_fingerprint failed", __func__);
1858                 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
1859                     sshkey_type(ctx->old_keys[i]), fp);
1860                 free(fp);
1861         }
1862         if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1863                 if (get_saved_tio() != NULL) {
1864                         leave_raw_mode(1);
1865                         was_raw = 1;
1866                 }
1867                 response = NULL;
1868                 for (i = 0; !quit_pending && i < 3; i++) {
1869                         free(response);
1870                         response = read_passphrase("Accept updated hostkeys? "
1871                             "(yes/no): ", RP_ECHO);
1872                         if (strcasecmp(response, "yes") == 0)
1873                                 break;
1874                         else if (quit_pending || response == NULL ||
1875                             strcasecmp(response, "no") == 0) {
1876                                 options.update_hostkeys = 0;
1877                                 break;
1878                         } else {
1879                                 do_log2(loglevel, "Please enter "
1880                                     "\"yes\" or \"no\"");
1881                         }
1882                 }
1883                 if (quit_pending || i >= 3 || response == NULL)
1884                         options.update_hostkeys = 0;
1885                 free(response);
1886                 if (was_raw)
1887                         enter_raw_mode(1);
1888         }
1889
1890         /*
1891          * Now that all the keys are verified, we can go ahead and replace
1892          * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
1893          * cancel the operation).
1894          */
1895         if (options.update_hostkeys != 0 &&
1896             (r = hostfile_replace_entries(options.user_hostfiles[0],
1897             ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
1898             options.hash_known_hosts, 0,
1899             options.fingerprint_hash)) != 0)
1900                 error("%s: hostfile_replace_entries failed: %s",
1901                     __func__, ssh_err(r));
1902 }
1903
1904 static void
1905 client_global_hostkeys_private_confirm(struct ssh *ssh, int type,
1906     u_int32_t seq, void *_ctx)
1907 {
1908         struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1909         size_t i, ndone;
1910         struct sshbuf *signdata;
1911         int r, kexsigtype, use_kexsigtype;
1912         const u_char *sig;
1913         size_t siglen;
1914
1915         if (ctx->nnew == 0)
1916                 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
1917         if (type != SSH2_MSG_REQUEST_SUCCESS) {
1918                 error("Server failed to confirm ownership of "
1919                     "private host keys");
1920                 hostkeys_update_ctx_free(ctx);
1921                 return;
1922         }
1923         kexsigtype = sshkey_type_plain(
1924             sshkey_type_from_name(ssh->kex->hostkey_alg));
1925
1926         if ((signdata = sshbuf_new()) == NULL)
1927                 fatal("%s: sshbuf_new failed", __func__);
1928         /* Don't want to accidentally accept an unbound signature */
1929         if (ssh->kex->session_id_len == 0)
1930                 fatal("%s: ssh->kex->session_id_len == 0", __func__);
1931         /*
1932          * Expect a signature for each of the ctx->nnew private keys we
1933          * haven't seen before. They will be in the same order as the
1934          * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
1935          */
1936         for (ndone = i = 0; i < ctx->nkeys; i++) {
1937                 if (ctx->keys_seen[i])
1938                         continue;
1939                 /* Prepare data to be signed: session ID, unique string, key */
1940                 sshbuf_reset(signdata);
1941                 if ( (r = sshbuf_put_cstring(signdata,
1942                     "hostkeys-prove-00@openssh.com")) != 0 ||
1943                     (r = sshbuf_put_string(signdata, ssh->kex->session_id,
1944                     ssh->kex->session_id_len)) != 0 ||
1945                     (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
1946                         fatal("%s: failed to prepare signature: %s",
1947                             __func__, ssh_err(r));
1948                 /* Extract and verify signature */
1949                 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
1950                         error("%s: couldn't parse message: %s",
1951                             __func__, ssh_err(r));
1952                         goto out;
1953                 }
1954                 /*
1955                  * For RSA keys, prefer to use the signature type negotiated
1956                  * during KEX to the default (SHA1).
1957                  */
1958                 use_kexsigtype = kexsigtype == KEY_RSA &&
1959                     sshkey_type_plain(ctx->keys[i]->type) == KEY_RSA;
1960                 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
1961                     sshbuf_ptr(signdata), sshbuf_len(signdata),
1962                     use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0)) != 0) {
1963                         error("%s: server gave bad signature for %s key %zu",
1964                             __func__, sshkey_type(ctx->keys[i]), i);
1965                         goto out;
1966                 }
1967                 /* Key is good. Mark it as 'seen' */
1968                 ctx->keys_seen[i] = 2;
1969                 ndone++;
1970         }
1971         if (ndone != ctx->nnew)
1972                 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
1973                     ndone, ctx->nnew);  /* Shouldn't happen */
1974         ssh_packet_check_eom(ssh);
1975
1976         /* Make the edits to known_hosts */
1977         update_known_hosts(ctx);
1978  out:
1979         hostkeys_update_ctx_free(ctx);
1980 }
1981
1982 /*
1983  * Returns non-zero if the key is accepted by HostkeyAlgorithms.
1984  * Made slightly less trivial by the multiple RSA signature algorithm names.
1985  */
1986 static int
1987 key_accepted_by_hostkeyalgs(const struct sshkey *key)
1988 {
1989         const char *ktype = sshkey_ssh_name(key);
1990         const char *hostkeyalgs = options.hostkeyalgorithms != NULL ?
1991             options.hostkeyalgorithms : KEX_DEFAULT_PK_ALG;
1992
1993         if (key == NULL || key->type == KEY_UNSPEC)
1994                 return 0;
1995         if (key->type == KEY_RSA &&
1996             (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
1997             match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
1998                 return 1;
1999         return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
2000 }
2001
2002 /*
2003  * Handle hostkeys-00@openssh.com global request to inform the client of all
2004  * the server's hostkeys. The keys are checked against the user's
2005  * HostkeyAlgorithms preference before they are accepted.
2006  */
2007 static int
2008 client_input_hostkeys(void)
2009 {
2010         struct ssh *ssh = active_state; /* XXX */
2011         const u_char *blob = NULL;
2012         size_t i, len = 0;
2013         struct sshbuf *buf = NULL;
2014         struct sshkey *key = NULL, **tmp;
2015         int r;
2016         char *fp;
2017         static int hostkeys_seen = 0; /* XXX use struct ssh */
2018         extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2019         struct hostkeys_update_ctx *ctx = NULL;
2020
2021         if (hostkeys_seen)
2022                 fatal("%s: server already sent hostkeys", __func__);
2023         if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2024             options.batch_mode)
2025                 return 1; /* won't ask in batchmode, so don't even try */
2026         if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2027                 return 1;
2028
2029         ctx = xcalloc(1, sizeof(*ctx));
2030         while (ssh_packet_remaining(ssh) > 0) {
2031                 sshkey_free(key);
2032                 key = NULL;
2033                 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2034                         error("%s: couldn't parse message: %s",
2035                             __func__, ssh_err(r));
2036                         goto out;
2037                 }
2038                 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2039                         error("%s: parse key: %s", __func__, ssh_err(r));
2040                         goto out;
2041                 }
2042                 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2043                     SSH_FP_DEFAULT);
2044                 debug3("%s: received %s key %s", __func__,
2045                     sshkey_type(key), fp);
2046                 free(fp);
2047
2048                 if (!key_accepted_by_hostkeyalgs(key)) {
2049                         debug3("%s: %s key not permitted by HostkeyAlgorithms",
2050                             __func__, sshkey_ssh_name(key));
2051                         continue;
2052                 }
2053                 /* Skip certs */
2054                 if (sshkey_is_cert(key)) {
2055                         debug3("%s: %s key is a certificate; skipping",
2056                             __func__, sshkey_ssh_name(key));
2057                         continue;
2058                 }
2059                 /* Ensure keys are unique */
2060                 for (i = 0; i < ctx->nkeys; i++) {
2061                         if (sshkey_equal(key, ctx->keys[i])) {
2062                                 error("%s: received duplicated %s host key",
2063                                     __func__, sshkey_ssh_name(key));
2064                                 goto out;
2065                         }
2066                 }
2067                 /* Key is good, record it */
2068                 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
2069                     sizeof(*ctx->keys))) == NULL)
2070                         fatal("%s: recallocarray failed nkeys = %zu",
2071                             __func__, ctx->nkeys);
2072                 ctx->keys = tmp;
2073                 ctx->keys[ctx->nkeys++] = key;
2074                 key = NULL;
2075         }
2076
2077         if (ctx->nkeys == 0) {
2078                 debug("%s: server sent no hostkeys", __func__);
2079                 goto out;
2080         }
2081
2082         if ((ctx->keys_seen = calloc(ctx->nkeys,
2083             sizeof(*ctx->keys_seen))) == NULL)
2084                 fatal("%s: calloc failed", __func__);
2085
2086         get_hostfile_hostname_ipaddr(host,
2087             options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2088             options.port, &ctx->host_str,
2089             options.check_host_ip ? &ctx->ip_str : NULL);
2090
2091         /* Find which keys we already know about. */
2092         if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2093             ctx, ctx->host_str, ctx->ip_str,
2094             HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2095                 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
2096                 goto out;
2097         }
2098
2099         /* Figure out if we have any new keys to add */
2100         ctx->nnew = 0;
2101         for (i = 0; i < ctx->nkeys; i++) {
2102                 if (!ctx->keys_seen[i])
2103                         ctx->nnew++;
2104         }
2105
2106         debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2107             __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2108
2109         if (ctx->nnew == 0 && ctx->nold != 0) {
2110                 /* We have some keys to remove. Just do it. */
2111                 update_known_hosts(ctx);
2112         } else if (ctx->nnew != 0) {
2113                 /*
2114                  * We have received hitherto-unseen keys from the server.
2115                  * Ask the server to confirm ownership of the private halves.
2116                  */
2117                 debug3("%s: asking server to prove ownership for %zu keys",
2118                     __func__, ctx->nnew);
2119                 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2120                     (r = sshpkt_put_cstring(ssh,
2121                     "hostkeys-prove-00@openssh.com")) != 0 ||
2122                     (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2123                         fatal("%s: cannot prepare packet: %s",
2124                             __func__, ssh_err(r));
2125                 if ((buf = sshbuf_new()) == NULL)
2126                         fatal("%s: sshbuf_new", __func__);
2127                 for (i = 0; i < ctx->nkeys; i++) {
2128                         if (ctx->keys_seen[i])
2129                                 continue;
2130                         sshbuf_reset(buf);
2131                         if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2132                                 fatal("%s: sshkey_putb: %s",
2133                                     __func__, ssh_err(r));
2134                         if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2135                                 fatal("%s: sshpkt_put_string: %s",
2136                                     __func__, ssh_err(r));
2137                 }
2138                 if ((r = sshpkt_send(ssh)) != 0)
2139                         fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2140                 client_register_global_confirm(
2141                     client_global_hostkeys_private_confirm, ctx);
2142                 ctx = NULL;  /* will be freed in callback */
2143         }
2144
2145         /* Success */
2146  out:
2147         hostkeys_update_ctx_free(ctx);
2148         sshkey_free(key);
2149         sshbuf_free(buf);
2150         /*
2151          * NB. Return success for all cases. The server doesn't need to know
2152          * what the client does with its hosts file.
2153          */
2154         return 1;
2155 }
2156
2157 static int
2158 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
2159 {
2160         char *rtype;
2161         int want_reply;
2162         int success = 0;
2163
2164         rtype = packet_get_cstring(NULL);
2165         want_reply = packet_get_char();
2166         debug("client_input_global_request: rtype %s want_reply %d",
2167             rtype, want_reply);
2168         if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2169                 success = client_input_hostkeys();
2170         if (want_reply) {
2171                 packet_start(success ?
2172                     SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2173                 packet_send();
2174                 packet_write_wait();
2175         }
2176         free(rtype);
2177         return 0;
2178 }
2179
2180 void
2181 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
2182     const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
2183     char **env)
2184 {
2185         int i, j, matched, len;
2186         char *name, *val;
2187         Channel *c = NULL;
2188
2189         debug2("%s: id %d", __func__, id);
2190
2191         if ((c = channel_lookup(ssh, id)) == NULL)
2192                 fatal("%s: channel %d: unknown channel", __func__, id);
2193
2194         packet_set_interactive(want_tty,
2195             options.ip_qos_interactive, options.ip_qos_bulk);
2196
2197         if (want_tty) {
2198                 struct winsize ws;
2199
2200                 /* Store window size in the packet. */
2201                 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2202                         memset(&ws, 0, sizeof(ws));
2203
2204                 channel_request_start(ssh, id, "pty-req", 1);
2205                 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
2206                 packet_put_cstring(term != NULL ? term : "");
2207                 packet_put_int((u_int)ws.ws_col);
2208                 packet_put_int((u_int)ws.ws_row);
2209                 packet_put_int((u_int)ws.ws_xpixel);
2210                 packet_put_int((u_int)ws.ws_ypixel);
2211                 if (tiop == NULL)
2212                         tiop = get_saved_tio();
2213                 ssh_tty_make_modes(ssh, -1, tiop);
2214                 packet_send();
2215                 /* XXX wait for reply */
2216                 c->client_tty = 1;
2217         }
2218
2219         /* Transfer any environment variables from client to server */
2220         if (options.num_send_env != 0 && env != NULL) {
2221                 debug("Sending environment.");
2222                 for (i = 0; env[i] != NULL; i++) {
2223                         /* Split */
2224                         name = xstrdup(env[i]);
2225                         if ((val = strchr(name, '=')) == NULL) {
2226                                 free(name);
2227                                 continue;
2228                         }
2229                         *val++ = '\0';
2230
2231                         matched = 0;
2232                         for (j = 0; j < options.num_send_env; j++) {
2233                                 if (match_pattern(name, options.send_env[j])) {
2234                                         matched = 1;
2235                                         break;
2236                                 }
2237                         }
2238                         if (!matched) {
2239                                 debug3("Ignored env %s", name);
2240                                 free(name);
2241                                 continue;
2242                         }
2243
2244                         debug("Sending env %s = %s", name, val);
2245                         channel_request_start(ssh, id, "env", 0);
2246                         packet_put_cstring(name);
2247                         packet_put_cstring(val);
2248                         packet_send();
2249                         free(name);
2250                 }
2251         }
2252         for (i = 0; i < options.num_setenv; i++) {
2253                 /* Split */
2254                 name = xstrdup(options.setenv[i]);
2255                 if ((val = strchr(name, '=')) == NULL) {
2256                         free(name);
2257                         continue;
2258                 }
2259                 *val++ = '\0';
2260
2261                 debug("Setting env %s = %s", name, val);
2262                 channel_request_start(ssh, id, "env", 0);
2263                 packet_put_cstring(name);
2264                 packet_put_cstring(val);
2265                 packet_send();
2266                 free(name);
2267         }
2268
2269         len = sshbuf_len(cmd);
2270         if (len > 0) {
2271                 if (len > 900)
2272                         len = 900;
2273                 if (want_subsystem) {
2274                         debug("Sending subsystem: %.*s",
2275                             len, (const u_char*)sshbuf_ptr(cmd));
2276                         channel_request_start(ssh, id, "subsystem", 1);
2277                         client_expect_confirm(ssh, id, "subsystem",
2278                             CONFIRM_CLOSE);
2279                 } else {
2280                         debug("Sending command: %.*s",
2281                             len, (const u_char*)sshbuf_ptr(cmd));
2282                         channel_request_start(ssh, id, "exec", 1);
2283                         client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
2284                 }
2285                 packet_put_string(sshbuf_ptr(cmd), sshbuf_len(cmd));
2286                 packet_send();
2287         } else {
2288                 channel_request_start(ssh, id, "shell", 1);
2289                 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
2290                 packet_send();
2291         }
2292 }
2293
2294 static void
2295 client_init_dispatch(void)
2296 {
2297         dispatch_init(&dispatch_protocol_error);
2298
2299         dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2300         dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2301         dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2302         dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2303         dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2304         dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2305         dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2306         dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2307         dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2308         dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2309         dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2310         dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2311
2312         /* rekeying */
2313         dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2314
2315         /* global request reply messages */
2316         dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2317         dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2318 }
2319
2320 void
2321 client_stop_mux(void)
2322 {
2323         if (options.control_path != NULL && muxserver_sock != -1)
2324                 unlink(options.control_path);
2325         /*
2326          * If we are in persist mode, or don't have a shell, signal that we
2327          * should close when all active channels are closed.
2328          */
2329         if (options.control_persist || no_shell_flag) {
2330                 session_closed = 1;
2331                 setproctitle("[stopped mux]");
2332         }
2333 }
2334
2335 /* client specific fatal cleanup */
2336 void
2337 cleanup_exit(int i)
2338 {
2339         leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2340         leave_non_blocking();
2341         if (options.control_path != NULL && muxserver_sock != -1)
2342                 unlink(options.control_path);
2343         ssh_kill_proxy_command();
2344         _exit(i);
2345 }