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