jcs's openbsd hax
openbsd
1/* $OpenBSD: clientloop.c,v 1.420 2026/02/14 00:18:34 jsg 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
63#include <sys/types.h>
64#include <sys/ioctl.h>
65#include <sys/stat.h>
66#include <sys/time.h>
67#include <sys/queue.h>
68
69#include <ctype.h>
70#include <errno.h>
71#include <paths.h>
72#include <poll.h>
73#include <signal.h>
74#include <stdio.h>
75#include <stdlib.h>
76#include <string.h>
77#include <stdarg.h>
78#include <unistd.h>
79#include <limits.h>
80
81#include "xmalloc.h"
82#include "ssh.h"
83#include "ssh2.h"
84#include "packet.h"
85#include "sshbuf.h"
86#include "compat.h"
87#include "channels.h"
88#include "dispatch.h"
89#include "sshkey.h"
90#include "kex.h"
91#include "log.h"
92#include "misc.h"
93#include "readconf.h"
94#include "clientloop.h"
95#include "sshconnect.h"
96#include "authfd.h"
97#include "atomicio.h"
98#include "sshpty.h"
99#include "match.h"
100#include "ssherr.h"
101#include "hostfile.h"
102
103/* Permitted RSA signature algorithms for UpdateHostkeys proofs */
104#define HOSTKEY_PROOF_RSA_ALGS "rsa-sha2-512,rsa-sha2-256"
105
106/* Uncertainty (in percent) of keystroke timing intervals */
107#define SSH_KEYSTROKE_TIMING_FUZZ 10
108
109/* import options */
110extern Options options;
111
112/* Control socket */
113extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
114
115/*
116 * Name of the host we are connecting to. This is the name given on the
117 * command line, or the Hostname specified for the user-supplied name in a
118 * configuration file.
119 */
120extern char *host;
121
122/*
123 * If this field is not NULL, the ForwardAgent socket is this path and different
124 * instead of SSH_AUTH_SOCK.
125 */
126extern char *forward_agent_sock_path;
127
128/*
129 * Flag to indicate that we have received a window change signal which has
130 * not yet been processed. This will cause a message indicating the new
131 * window size to be sent to the server a little later. This is volatile
132 * because this is updated in a signal handler.
133 */
134static volatile sig_atomic_t received_window_change_signal = 0;
135static volatile sig_atomic_t siginfo_received = 0;
136static volatile sig_atomic_t received_signal = 0; /* exit signals */
137
138/* Time when backgrounded control master using ControlPersist should exit */
139static time_t control_persist_exit_time = 0;
140
141/* Common data for the client loop code. */
142volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
143static int last_was_cr; /* Last character was a newline. */
144static int exit_status; /* Used to store the command exit status. */
145static int connection_in; /* Connection to server (input). */
146static int connection_out; /* Connection to server (output). */
147static int need_rekeying; /* Set to non-zero if rekeying is requested. */
148static int session_closed; /* In SSH2: login session closed. */
149static time_t x11_refuse_time; /* If >0, refuse x11 opens after this time. */
150static time_t server_alive_time; /* Time to do server_alive_check */
151static int hostkeys_update_complete;
152static int session_setup_complete;
153
154static void client_init_dispatch(struct ssh *ssh);
155int session_ident = -1;
156
157/* Track escape per proto2 channel */
158struct escape_filter_ctx {
159 int escape_pending;
160 int escape_char;
161};
162
163/* Context for channel confirmation replies */
164struct channel_reply_ctx {
165 const char *request_type;
166 int id;
167 enum confirm_action action;
168};
169
170/* Global request success/failure callbacks */
171/* XXX move to struct ssh? */
172struct global_confirm {
173 TAILQ_ENTRY(global_confirm) entry;
174 global_confirm_cb *cb;
175 void *ctx;
176 int ref_count;
177};
178TAILQ_HEAD(global_confirms, global_confirm);
179static struct global_confirms global_confirms =
180 TAILQ_HEAD_INITIALIZER(global_confirms);
181
182static void quit_message(const char *fmt, ...)
183 __attribute__((__format__ (printf, 1, 2)));
184
185static void
186quit_message(const char *fmt, ...)
187{
188 char *msg, *fmt2;
189 va_list args;
190 xasprintf(&fmt2, "%s\r\n", fmt);
191
192 va_start(args, fmt);
193 xvasprintf(&msg, fmt2, args);
194 va_end(args);
195
196 (void)atomicio(vwrite, STDERR_FILENO, msg, strlen(msg));
197 free(msg);
198 free(fmt2);
199
200 quit_pending = 1;
201}
202
203/*
204 * Signal handler for the window change signal (SIGWINCH). This just sets a
205 * flag indicating that the window has changed.
206 */
207static void
208window_change_handler(int sig)
209{
210 received_window_change_signal = 1;
211}
212
213/* Signal handler for SIGINFO */
214static void
215siginfo_handler(int sig)
216{
217 siginfo_received = 1;
218}
219
220/*
221 * Signal handler for signals that cause the program to terminate. These
222 * signals must be trapped to restore terminal modes.
223 */
224static void
225signal_handler(int sig)
226{
227 received_signal = sig;
228 quit_pending = 1;
229}
230
231/*
232 * Sets control_persist_exit_time to the absolute time when the
233 * backgrounded control master should exit due to expiry of the
234 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
235 * control master process, or if there is no ControlPersist timeout.
236 */
237static void
238set_control_persist_exit_time(struct ssh *ssh)
239{
240 if (muxserver_sock == -1 || !options.control_persist
241 || options.control_persist_timeout == 0) {
242 /* not using a ControlPersist timeout */
243 control_persist_exit_time = 0;
244 } else if (channel_still_open(ssh)) {
245 /* some client connections are still open */
246 if (control_persist_exit_time > 0)
247 debug2_f("cancel scheduled exit");
248 control_persist_exit_time = 0;
249 } else if (control_persist_exit_time <= 0) {
250 /* a client connection has recently closed */
251 control_persist_exit_time = monotime() +
252 (time_t)options.control_persist_timeout;
253 debug2_f("schedule exit in %d seconds",
254 options.control_persist_timeout);
255 }
256 /* else we are already counting down to the timeout */
257}
258
259#define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
260static int
261client_x11_display_valid(const char *display)
262{
263 size_t i, dlen;
264
265 if (display == NULL)
266 return 0;
267
268 dlen = strlen(display);
269 for (i = 0; i < dlen; i++) {
270 if (!isalnum((u_char)display[i]) &&
271 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
272 debug("Invalid character '%c' in DISPLAY", display[i]);
273 return 0;
274 }
275 }
276 return 1;
277}
278
279#define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
280#define X11_TIMEOUT_SLACK 60
281int
282client_x11_get_proto(struct ssh *ssh, const char *display,
283 const char *xauth_path, u_int trusted, u_int timeout,
284 char **_proto, char **_data)
285{
286 char *cmd, line[512], xdisplay[512];
287 char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
288 static char proto[512], data[512];
289 FILE *f;
290 int got_data = 0, generated = 0, do_unlink = 0, r;
291 struct stat st;
292 u_int now, x11_timeout_real;
293
294 *_proto = proto;
295 *_data = data;
296 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
297
298 if (!client_x11_display_valid(display)) {
299 if (display != NULL)
300 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
301 display);
302 return -1;
303 }
304 if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
305 debug("No xauth program.");
306 xauth_path = NULL;
307 }
308
309 if (xauth_path != NULL) {
310 /*
311 * Handle FamilyLocal case where $DISPLAY does
312 * not match an authorization entry. For this we
313 * just try "xauth list unix:displaynum.screennum".
314 * XXX: "localhost" match to determine FamilyLocal
315 * is not perfect.
316 */
317 if (strncmp(display, "localhost:", 10) == 0) {
318 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
319 display + 10)) < 0 ||
320 (size_t)r >= sizeof(xdisplay)) {
321 error_f("display name too long");
322 return -1;
323 }
324 display = xdisplay;
325 }
326 if (trusted == 0) {
327 /*
328 * Generate an untrusted X11 auth cookie.
329 *
330 * The authentication cookie should briefly outlive
331 * ssh's willingness to forward X11 connections to
332 * avoid nasty fail-open behaviour in the X server.
333 */
334 mktemp_proto(xauthdir, sizeof(xauthdir));
335 if (mkdtemp(xauthdir) == NULL) {
336 error_f("mkdtemp: %s", strerror(errno));
337 return -1;
338 }
339 do_unlink = 1;
340 if ((r = snprintf(xauthfile, sizeof(xauthfile),
341 "%s/xauthfile", xauthdir)) < 0 ||
342 (size_t)r >= sizeof(xauthfile)) {
343 error_f("xauthfile path too long");
344 rmdir(xauthdir);
345 return -1;
346 }
347
348 if (timeout == 0) {
349 /* auth doesn't time out */
350 xasprintf(&cmd, "%s -f %s generate %s %s "
351 "untrusted 2>%s",
352 xauth_path, xauthfile, display,
353 SSH_X11_PROTO, _PATH_DEVNULL);
354 } else {
355 /* Add some slack to requested expiry */
356 if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
357 x11_timeout_real = timeout +
358 X11_TIMEOUT_SLACK;
359 else {
360 /* Don't overflow on long timeouts */
361 x11_timeout_real = UINT_MAX;
362 }
363 xasprintf(&cmd, "%s -f %s generate %s %s "
364 "untrusted timeout %u 2>%s",
365 xauth_path, xauthfile, display,
366 SSH_X11_PROTO, x11_timeout_real,
367 _PATH_DEVNULL);
368 }
369 debug2_f("xauth command: %s", cmd);
370
371 if (timeout != 0 && x11_refuse_time == 0) {
372 now = monotime() + 1;
373 if (SSH_TIME_T_MAX - timeout < now)
374 x11_refuse_time = SSH_TIME_T_MAX;
375 else
376 x11_refuse_time = now + timeout;
377 channel_set_x11_refuse_time(ssh,
378 x11_refuse_time);
379 }
380 if (system(cmd) == 0)
381 generated = 1;
382 free(cmd);
383 }
384
385 /*
386 * When in untrusted mode, we read the cookie only if it was
387 * successfully generated as an untrusted one in the step
388 * above.
389 */
390 if (trusted || generated) {
391 xasprintf(&cmd,
392 "%s %s%s list %s 2>" _PATH_DEVNULL,
393 xauth_path,
394 generated ? "-f " : "" ,
395 generated ? xauthfile : "",
396 display);
397 debug2("x11_get_proto: %s", cmd);
398 f = popen(cmd, "r");
399 if (f && fgets(line, sizeof(line), f) &&
400 sscanf(line, "%*s %511s %511s", proto, data) == 2)
401 got_data = 1;
402 if (f)
403 pclose(f);
404 free(cmd);
405 }
406 }
407
408 if (do_unlink) {
409 unlink(xauthfile);
410 rmdir(xauthdir);
411 }
412
413 /* Don't fall back to fake X11 data for untrusted forwarding */
414 if (!trusted && !got_data) {
415 error("Warning: untrusted X11 forwarding setup failed: "
416 "xauth key data not generated");
417 return -1;
418 }
419
420 /*
421 * If we didn't get authentication data, just make up some
422 * data. The forwarding code will check the validity of the
423 * response anyway, and substitute this data. The X11
424 * server, however, will ignore this fake data and use
425 * whatever authentication mechanisms it was using otherwise
426 * for the local connection.
427 */
428 if (!got_data) {
429 u_int8_t rnd[16];
430 u_int i;
431
432 logit("Warning: No xauth data; "
433 "using fake authentication data for X11 forwarding.");
434 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
435 arc4random_buf(rnd, sizeof(rnd));
436 for (i = 0; i < sizeof(rnd); i++) {
437 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
438 rnd[i]);
439 }
440 }
441
442 return 0;
443}
444
445/*
446 * Checks if the client window has changed, and sends a packet about it to
447 * the server if so. The actual change is detected elsewhere (by a software
448 * interrupt on Unix); this just checks the flag and sends a message if
449 * appropriate.
450 */
451
452static void
453client_check_window_change(struct ssh *ssh)
454{
455 if (!received_window_change_signal)
456 return;
457 received_window_change_signal = 0;
458 debug2_f("changed");
459 channel_send_window_changes(ssh);
460}
461
462static int
463client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
464{
465 struct global_confirm *gc;
466
467 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
468 return 0;
469 if (gc->cb != NULL)
470 gc->cb(ssh, type, seq, gc->ctx);
471 if (--gc->ref_count <= 0) {
472 TAILQ_REMOVE(&global_confirms, gc, entry);
473 freezero(gc, sizeof(*gc));
474 }
475
476 ssh_packet_set_alive_timeouts(ssh, 0);
477 return 0;
478}
479
480static void
481schedule_server_alive_check(void)
482{
483 if (options.server_alive_interval > 0)
484 server_alive_time = monotime() + options.server_alive_interval;
485}
486
487static void
488server_alive_check(struct ssh *ssh)
489{
490 int r;
491
492 if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) {
493 logit("Timeout, server %s not responding.", host);
494 cleanup_exit(255);
495 }
496 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
497 (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 ||
498 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* boolean: want reply */
499 (r = sshpkt_send(ssh)) != 0)
500 fatal_fr(r, "send packet");
501 /* Insert an empty placeholder to maintain ordering */
502 client_register_global_confirm(NULL, NULL);
503 schedule_server_alive_check();
504}
505
506/* Try to send a dummy keystroke */
507static int
508send_chaff(struct ssh *ssh)
509{
510 int r;
511
512 if (ssh->kex == NULL || (ssh->kex->flags & KEX_HAS_PING) == 0)
513 return 0;
514 /* XXX probabilistically send chaff? */
515 /*
516 * a SSH2_MSG_CHANNEL_DATA payload is 9 bytes:
517 * 4 bytes channel ID + 4 bytes string length + 1 byte string data
518 * simulate that here.
519 */
520 if ((r = sshpkt_start(ssh, SSH2_MSG_PING)) != 0 ||
521 (r = sshpkt_put_cstring(ssh, "PING!")) != 0 ||
522 (r = sshpkt_send(ssh)) != 0)
523 fatal_fr(r, "send packet");
524 return 1;
525}
526
527/* Sets the next interval to send a keystroke or chaff packet */
528static void
529set_next_interval(const struct timespec *now, struct timespec *next_interval,
530 u_int interval_ms, int starting)
531{
532 struct timespec tmp;
533 long long interval_ns, fuzz_ns;
534 static long long rate_fuzz;
535
536 interval_ns = interval_ms * (1000LL * 1000);
537 fuzz_ns = (interval_ns * SSH_KEYSTROKE_TIMING_FUZZ) / 100;
538 /* Center fuzz around requested interval */
539 if (fuzz_ns > INT_MAX)
540 fuzz_ns = INT_MAX;
541 if (fuzz_ns > interval_ns) {
542 /* Shouldn't happen */
543 fatal_f("internal error: fuzz %u%% %lldns > interval %lldns",
544 SSH_KEYSTROKE_TIMING_FUZZ, fuzz_ns, interval_ns);
545 }
546 /*
547 * Randomise the keystroke/chaff intervals in two ways:
548 * 1. Each interval has some random jitter applied to make the
549 * interval-to-interval time unpredictable.
550 * 2. The overall interval rate is also randomly perturbed for each
551 * chaffing session to make the average rate unpredictable.
552 */
553 if (starting)
554 rate_fuzz = arc4random_uniform(fuzz_ns);
555 interval_ns -= fuzz_ns;
556 interval_ns += arc4random_uniform(fuzz_ns) + rate_fuzz;
557
558 tmp.tv_sec = interval_ns / (1000 * 1000 * 1000);
559 tmp.tv_nsec = interval_ns % (1000 * 1000 * 1000);
560
561 timespecadd(now, &tmp, next_interval);
562}
563
564/*
565 * Performs keystroke timing obfuscation. Returns non-zero if the
566 * output fd should be polled.
567 */
568static int
569obfuscate_keystroke_timing(struct ssh *ssh, struct timespec *timeout,
570 int channel_did_enqueue)
571{
572 static int active;
573 static struct timespec next_interval, chaff_until;
574 struct timespec now, tmp;
575 int just_started = 0, had_keystroke = 0;
576 static unsigned long long nchaff;
577 char *stop_reason = NULL;
578 long long n;
579
580 monotime_ts(&now);
581
582 if (options.obscure_keystroke_timing_interval <= 0)
583 return 1; /* disabled in config */
584
585 if (!channel_tty_open(ssh) || quit_pending) {
586 /* Stop if no channels left of we're waiting for one to close */
587 stop_reason = "no active channels";
588 } else if (ssh_packet_is_rekeying(ssh)) {
589 /* Stop if we're rekeying */
590 stop_reason = "rekeying started";
591 } else if (!ssh_packet_interactive_data_to_write(ssh) &&
592 ssh_packet_have_data_to_write(ssh)) {
593 /* Stop if the output buffer has more than a few keystrokes */
594 stop_reason = "output buffer filling";
595 } else if (active && channel_did_enqueue &&
596 ssh_packet_have_data_to_write(ssh)) {
597 /* Still in active mode and have a keystroke queued. */
598 had_keystroke = 1;
599 } else if (active) {
600 if (timespeccmp(&now, &chaff_until, >=)) {
601 /* Stop if there have been no keystrokes for a while */
602 stop_reason = "chaff time expired";
603 } else if (timespeccmp(&now, &next_interval, >=) &&
604 !ssh_packet_have_data_to_write(ssh)) {
605 /* If due to send but have no data, then send chaff */
606 if (send_chaff(ssh))
607 nchaff++;
608 }
609 }
610
611 if (stop_reason != NULL) {
612 if (active) {
613 debug3_f("stopping: %s (%llu chaff packets sent)",
614 stop_reason, nchaff);
615 active = 0;
616 }
617 return 1;
618 }
619
620 /*
621 * If we're in interactive mode, and only have a small amount
622 * of outbound data, then we assume that the user is typing
623 * interactively. In this case, start quantising outbound packets to
624 * fixed time intervals to hide inter-keystroke timing.
625 */
626 if (!active && ssh_packet_interactive_data_to_write(ssh) &&
627 channel_did_enqueue && ssh_packet_have_data_to_write(ssh)) {
628 debug3_f("starting: interval ~%dms",
629 options.obscure_keystroke_timing_interval);
630 just_started = had_keystroke = active = 1;
631 nchaff = 0;
632 set_next_interval(&now, &next_interval,
633 options.obscure_keystroke_timing_interval, 1);
634 }
635
636 /* Don't hold off if obfuscation inactive */
637 if (!active)
638 return 1;
639
640 if (had_keystroke) {
641 /*
642 * Arrange to send chaff packets for a random interval after
643 * the last keystroke was sent.
644 */
645 ms_to_timespec(&tmp, SSH_KEYSTROKE_CHAFF_MIN_MS +
646 arc4random_uniform(SSH_KEYSTROKE_CHAFF_RNG_MS));
647 timespecadd(&now, &tmp, &chaff_until);
648 }
649
650 ptimeout_deadline_monotime_tsp(timeout, &next_interval);
651
652 if (just_started)
653 return 1;
654
655 /* Don't arm output fd for poll until the timing interval has elapsed... */
656 if (timespeccmp(&now, &next_interval, <))
657 /* ...unless there's x11 communication happening */
658 return x11_channel_used_recently(ssh);
659
660 /* Calculate number of intervals missed since the last check */
661 n = (now.tv_sec - next_interval.tv_sec) * 1000LL * 1000 * 1000;
662 n += now.tv_nsec - next_interval.tv_nsec;
663 n /= options.obscure_keystroke_timing_interval * 1000LL * 1000;
664 n = (n < 0) ? 1 : n + 1;
665
666 /* Advance to the next interval */
667 set_next_interval(&now, &next_interval,
668 options.obscure_keystroke_timing_interval * n, 0);
669 return 1;
670}
671
672/*
673 * Waits until the client can do something (some data becomes available on
674 * one of the file descriptors).
675 */
676static void
677client_wait_until_can_do_something(struct ssh *ssh, struct pollfd **pfdp,
678 u_int *npfd_allocp, u_int *npfd_activep, int channel_did_enqueue,
679 sigset_t *sigsetp, int *conn_in_readyp, int *conn_out_readyp)
680{
681 struct timespec timeout;
682 int ret, oready;
683 u_int p;
684
685 *conn_in_readyp = *conn_out_readyp = 0;
686
687 /* Prepare channel poll. First two pollfd entries are reserved */
688 ptimeout_init(&timeout);
689 channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout);
690 if (*npfd_activep < 2)
691 fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */
692
693 /* channel_prepare_poll could have closed the last channel */
694 if (session_closed && !channel_still_open(ssh) &&
695 !ssh_packet_have_data_to_write(ssh)) {
696 /* clear events since we did not call poll() */
697 for (p = 0; p < *npfd_activep; p++)
698 (*pfdp)[p].revents = 0;
699 return;
700 }
701
702 oready = obfuscate_keystroke_timing(ssh, &timeout, channel_did_enqueue);
703
704 /* Monitor server connection on reserved pollfd entries */
705 (*pfdp)[0].fd = connection_in;
706 (*pfdp)[0].events = POLLIN;
707 (*pfdp)[1].fd = connection_out;
708 (*pfdp)[1].events = (oready && ssh_packet_have_data_to_write(ssh)) ?
709 POLLOUT : 0;
710
711 /*
712 * Wait for something to happen. This will suspend the process until
713 * some polled descriptor can be read, written, or has some other
714 * event pending, or a timeout expires.
715 */
716 set_control_persist_exit_time(ssh);
717 if (control_persist_exit_time > 0)
718 ptimeout_deadline_monotime(&timeout, control_persist_exit_time);
719 if (options.server_alive_interval > 0)
720 ptimeout_deadline_monotime(&timeout, server_alive_time);
721 if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) {
722 ptimeout_deadline_sec(&timeout,
723 ssh_packet_get_rekey_timeout(ssh));
724 }
725
726 ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), sigsetp);
727
728 if (ret == -1) {
729 /*
730 * We have to clear the events because we return.
731 * We have to return, because the mainloop checks for the flags
732 * set by the signal handlers.
733 */
734 for (p = 0; p < *npfd_activep; p++)
735 (*pfdp)[p].revents = 0;
736 if (errno == EINTR)
737 return;
738 /* Note: we might still have data in the buffers. */
739 quit_message("poll: %s", strerror(errno));
740 return;
741 }
742
743 *conn_in_readyp = (*pfdp)[0].revents != 0;
744 *conn_out_readyp = (*pfdp)[1].revents != 0;
745
746 if (options.server_alive_interval > 0 && !*conn_in_readyp &&
747 monotime() >= server_alive_time) {
748 /*
749 * ServerAlive check is needed. We can't rely on the poll
750 * timing out since traffic on the client side such as port
751 * forwards can keep waking it up.
752 */
753 server_alive_check(ssh);
754 }
755}
756
757static void
758client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
759{
760 /* Flush stdout and stderr buffers. */
761 if (sshbuf_len(bout) > 0)
762 atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
763 sshbuf_len(bout));
764 if (sshbuf_len(berr) > 0)
765 atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
766 sshbuf_len(berr));
767
768 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
769
770 sshbuf_reset(bin);
771 sshbuf_reset(bout);
772 sshbuf_reset(berr);
773
774 /* Send the suspend signal to the program itself. */
775 kill(getpid(), SIGTSTP);
776
777 /* Reset window sizes in case they have changed */
778 received_window_change_signal = 1;
779
780 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
781}
782
783static void
784client_process_net_input(struct ssh *ssh)
785{
786 int r;
787
788 /*
789 * Read input from the server, and add any such data to the buffer of
790 * the packet subsystem.
791 */
792 schedule_server_alive_check();
793 if ((r = ssh_packet_process_read(ssh, connection_in)) == 0)
794 return; /* success */
795 if (r == SSH_ERR_SYSTEM_ERROR) {
796 if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK)
797 return;
798 if (errno == EPIPE) {
799 quit_message("Connection to %s closed by remote host.",
800 host);
801 return;
802 }
803 }
804 quit_message("Read from remote host %s: %s", host, ssh_err(r));
805}
806
807static void
808client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
809{
810 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
811 char errmsg[256];
812 int r, tochan;
813
814 /*
815 * If a TTY was explicitly requested, then a failure to allocate
816 * one is fatal.
817 */
818 if (cr->action == CONFIRM_TTY &&
819 (options.request_tty == REQUEST_TTY_FORCE ||
820 options.request_tty == REQUEST_TTY_YES))
821 cr->action = CONFIRM_CLOSE;
822
823 /* XXX suppress on mux _client_ quietmode */
824 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
825 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
826
827 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
828 debug2("%s request accepted on channel %d",
829 cr->request_type, c->self);
830 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
831 if (tochan) {
832 snprintf(errmsg, sizeof(errmsg),
833 "%s request failed\r\n", cr->request_type);
834 } else {
835 snprintf(errmsg, sizeof(errmsg),
836 "%s request failed on channel %d",
837 cr->request_type, c->self);
838 }
839 /* If error occurred on primary session channel, then exit */
840 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
841 fatal("%s", errmsg);
842 /*
843 * If error occurred on mux client, append to
844 * their stderr.
845 */
846 if (tochan) {
847 debug3_f("channel %d: mux request: %s", c->self,
848 cr->request_type);
849 if ((r = sshbuf_put(c->extended, errmsg,
850 strlen(errmsg))) != 0)
851 fatal_fr(r, "sshbuf_put");
852 } else
853 error("%s", errmsg);
854 if (cr->action == CONFIRM_TTY) {
855 /*
856 * If a TTY allocation error occurred, then arrange
857 * for the correct TTY to leave raw mode.
858 */
859 if (c->self == session_ident)
860 leave_raw_mode(0);
861 else
862 mux_tty_alloc_failed(ssh, c);
863 } else if (cr->action == CONFIRM_CLOSE) {
864 chan_read_failed(ssh, c);
865 chan_write_failed(ssh, c);
866 }
867 }
868 free(cr);
869}
870
871static void
872client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
873{
874 free(ctx);
875}
876
877void
878client_expect_confirm(struct ssh *ssh, int id, const char *request,
879 enum confirm_action action)
880{
881 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
882
883 cr->request_type = request;
884 cr->action = action;
885
886 channel_register_status_confirm(ssh, id, client_status_confirm,
887 client_abandon_status_confirm, cr);
888}
889
890void
891client_register_global_confirm(global_confirm_cb *cb, void *ctx)
892{
893 struct global_confirm *gc, *last_gc;
894
895 /* Coalesce identical callbacks */
896 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
897 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
898 if (++last_gc->ref_count >= INT_MAX)
899 fatal_f("last_gc->ref_count = %d",
900 last_gc->ref_count);
901 return;
902 }
903
904 gc = xcalloc(1, sizeof(*gc));
905 gc->cb = cb;
906 gc->ctx = ctx;
907 gc->ref_count = 1;
908 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
909}
910
911/*
912 * Returns non-zero if the client is able to handle a hostkeys-00@openssh.com
913 * hostkey update request.
914 */
915static int
916can_update_hostkeys(void)
917{
918 if (hostkeys_update_complete)
919 return 0;
920 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
921 options.batch_mode)
922 return 0; /* won't ask in batchmode, so don't even try */
923 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
924 return 0;
925 return 1;
926}
927
928static void
929client_repledge(void)
930{
931 debug3_f("enter");
932
933 /* Might be able to tighten pledge now that session is established */
934 if (options.control_master || options.control_path != NULL ||
935 options.forward_x11 || options.fork_after_authentication ||
936 options.pkcs11_provider != NULL || can_update_hostkeys() ||
937 (session_ident != -1 && !session_setup_complete)) {
938 /* Can't tighten */
939 return;
940 }
941 /*
942 * LocalCommand and UpdateHostkeys have finished, so can get rid of
943 * filesystem.
944 *
945 * XXX protocol allows a server can to change hostkeys during the
946 * connection at rekey time that could trigger a hostkeys update
947 * but AFAIK no implementations support this. Could improve by
948 * forcing known_hosts to be read-only or via unveil(2).
949 */
950 if (options.num_local_forwards != 0 ||
951 options.num_remote_forwards != 0 ||
952 options.num_permitted_remote_opens != 0 ||
953 options.enable_escape_commandline != 0) {
954 /* rfwd needs inet */
955 debug("pledge: network");
956 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
957 fatal_f("pledge(): %s", strerror(errno));
958 } else if (options.forward_agent != 0) {
959 /* agent forwarding needs to open $SSH_AUTH_SOCK at will */
960 debug("pledge: agent");
961 if (pledge("stdio unix proc tty", NULL) == -1)
962 fatal_f("pledge(): %s", strerror(errno));
963 } else {
964 debug("pledge: fork");
965 if (pledge("stdio proc tty", NULL) == -1)
966 fatal_f("pledge(): %s", strerror(errno));
967 }
968 /* XXX further things to do:
969 *
970 * - might be able to get rid of proc if we kill ~^Z
971 * - ssh -N (no session)
972 * - stdio forwarding
973 * - sessions without tty
974 */
975}
976
977static void
978process_cmdline(struct ssh *ssh)
979{
980 void (*handler)(int);
981 char *s, *cmd;
982 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
983 struct Forward fwd;
984
985 memset(&fwd, 0, sizeof(fwd));
986
987 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
988 handler = ssh_signal(SIGINT, SIG_IGN);
989 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
990 if (s == NULL)
991 goto out;
992 while (isspace((u_char)*s))
993 s++;
994 if (*s == '-')
995 s++; /* Skip cmdline '-', if any */
996 if (*s == '\0')
997 goto out;
998
999 if (*s == 'h' || *s == 'H' || *s == '?') {
1000 logit("Commands:");
1001 logit(" -L[bind_address:]port:host:hostport "
1002 "Request local forward");
1003 logit(" -R[bind_address:]port:host:hostport "
1004 "Request remote forward");
1005 logit(" -D[bind_address:]port "
1006 "Request dynamic forward");
1007 logit(" -KL[bind_address:]port "
1008 "Cancel local forward");
1009 logit(" -KR[bind_address:]port "
1010 "Cancel remote forward");
1011 logit(" -KD[bind_address:]port "
1012 "Cancel dynamic forward");
1013 if (!options.permit_local_command)
1014 goto out;
1015 logit(" !args "
1016 "Execute local command");
1017 goto out;
1018 }
1019
1020 if (*s == '!' && options.permit_local_command) {
1021 s++;
1022 ssh_local_cmd(s);
1023 goto out;
1024 }
1025
1026 if (*s == 'K') {
1027 delete = 1;
1028 s++;
1029 }
1030 if (*s == 'L')
1031 local = 1;
1032 else if (*s == 'R')
1033 remote = 1;
1034 else if (*s == 'D')
1035 dynamic = 1;
1036 else {
1037 logit("Invalid command.");
1038 goto out;
1039 }
1040
1041 while (isspace((u_char)*++s))
1042 ;
1043
1044 /* XXX update list of forwards in options */
1045 if (delete) {
1046 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
1047 if (!parse_forward(&fwd, s, 1, 0)) {
1048 logit("Bad forwarding close specification.");
1049 goto out;
1050 }
1051 if (remote)
1052 ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
1053 else if (dynamic)
1054 ok = channel_cancel_lport_listener(ssh, &fwd,
1055 0, &options.fwd_opts) > 0;
1056 else
1057 ok = channel_cancel_lport_listener(ssh, &fwd,
1058 CHANNEL_CANCEL_PORT_STATIC,
1059 &options.fwd_opts) > 0;
1060 if (!ok) {
1061 logit("Unknown port forwarding.");
1062 goto out;
1063 }
1064 logit("Canceled forwarding.");
1065 } else {
1066 /* -R specs can be both dynamic or not, so check both. */
1067 if (remote) {
1068 if (!parse_forward(&fwd, s, 0, remote) &&
1069 !parse_forward(&fwd, s, 1, remote)) {
1070 logit("Bad remote forwarding specification.");
1071 goto out;
1072 }
1073 } else if (!parse_forward(&fwd, s, dynamic, remote)) {
1074 logit("Bad local forwarding specification.");
1075 goto out;
1076 }
1077 if (local || dynamic) {
1078 if (!channel_setup_local_fwd_listener(ssh, &fwd,
1079 &options.fwd_opts)) {
1080 logit("Port forwarding failed.");
1081 goto out;
1082 }
1083 } else {
1084 if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
1085 logit("Port forwarding failed.");
1086 goto out;
1087 }
1088 }
1089 logit("Forwarding port.");
1090 }
1091
1092out:
1093 ssh_signal(SIGINT, handler);
1094 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1095 free(cmd);
1096 free(fwd.listen_host);
1097 free(fwd.listen_path);
1098 free(fwd.connect_host);
1099 free(fwd.connect_path);
1100}
1101
1102/* reasons to suppress output of an escape command in help output */
1103#define SUPPRESS_NEVER 0 /* never suppress, always show */
1104#define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
1105#define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
1106#define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
1107#define SUPPRESS_NOCMDLINE 8 /* don't show when cmdline disabled*/
1108struct escape_help_text {
1109 const char *cmd;
1110 const char *text;
1111 unsigned int flags;
1112};
1113static struct escape_help_text esc_txt[] = {
1114 {".", "terminate session", SUPPRESS_MUXMASTER},
1115 {".", "terminate connection (and any multiplexed sessions)",
1116 SUPPRESS_MUXCLIENT},
1117 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
1118 {"C", "open a command line", SUPPRESS_MUXCLIENT|SUPPRESS_NOCMDLINE},
1119 {"I", "show connection information", SUPPRESS_NEVER},
1120 {"R", "request rekey", SUPPRESS_NEVER},
1121 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1122 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1123 {"#", "list forwarded connections", SUPPRESS_NEVER},
1124 {"&", "background ssh (when waiting for connections to terminate)",
1125 SUPPRESS_MUXCLIENT},
1126 {"?", "this message", SUPPRESS_NEVER},
1127};
1128
1129static void
1130print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
1131 int using_stderr)
1132{
1133 unsigned int i, suppress_flags;
1134 int r;
1135
1136 if ((r = sshbuf_putf(b,
1137 "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
1138 fatal_fr(r, "sshbuf_putf");
1139
1140 suppress_flags =
1141 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1142 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1143 (using_stderr ? 0 : SUPPRESS_SYSLOG) |
1144 (options.enable_escape_commandline == 0 ? SUPPRESS_NOCMDLINE : 0);
1145
1146 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1147 if (esc_txt[i].flags & suppress_flags)
1148 continue;
1149 if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
1150 escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
1151 fatal_fr(r, "sshbuf_putf");
1152 }
1153
1154 if ((r = sshbuf_putf(b,
1155 " %c%c - send the escape character by typing it twice\r\n"
1156 "(Note that escapes are only recognized immediately after "
1157 "newline.)\r\n", escape_char, escape_char)) != 0)
1158 fatal_fr(r, "sshbuf_putf");
1159}
1160
1161/*
1162 * Process the characters one by one.
1163 */
1164static int
1165process_escapes(struct ssh *ssh, Channel *c,
1166 struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
1167 char *buf, int len)
1168{
1169 pid_t pid;
1170 int r, bytes = 0;
1171 u_int i;
1172 u_char ch;
1173 char *s;
1174 struct escape_filter_ctx *efc;
1175
1176 if (c == NULL || c->filter_ctx == NULL || len <= 0)
1177 return 0;
1178
1179 efc = (struct escape_filter_ctx *)c->filter_ctx;
1180
1181 for (i = 0; i < (u_int)len; i++) {
1182 /* Get one character at a time. */
1183 ch = buf[i];
1184
1185 if (efc->escape_pending) {
1186 /* We have previously seen an escape character. */
1187 /* Clear the flag now. */
1188 efc->escape_pending = 0;
1189
1190 /* Process the escaped character. */
1191 switch (ch) {
1192 case '.':
1193 /* Terminate the connection. */
1194 if ((r = sshbuf_putf(berr, "%c.\r\n",
1195 efc->escape_char)) != 0)
1196 fatal_fr(r, "sshbuf_putf");
1197 if (c && c->ctl_chan != -1) {
1198 channel_force_close(ssh, c, 1);
1199 return 0;
1200 } else
1201 quit_pending = 1;
1202 return -1;
1203
1204 case 'Z' - 64:
1205 /* XXX support this for mux clients */
1206 if (c && c->ctl_chan != -1) {
1207 char b[16];
1208 noescape:
1209 if (ch == 'Z' - 64)
1210 snprintf(b, sizeof b, "^Z");
1211 else
1212 snprintf(b, sizeof b, "%c", ch);
1213 if ((r = sshbuf_putf(berr,
1214 "%c%s escape not available to "
1215 "multiplexed sessions\r\n",
1216 efc->escape_char, b)) != 0)
1217 fatal_fr(r, "sshbuf_putf");
1218 continue;
1219 }
1220 /* Suspend the program. Inform the user */
1221 if ((r = sshbuf_putf(berr,
1222 "%c^Z [suspend ssh]\r\n",
1223 efc->escape_char)) != 0)
1224 fatal_fr(r, "sshbuf_putf");
1225
1226 /* Restore terminal modes and suspend. */
1227 client_suspend_self(bin, bout, berr);
1228
1229 /* We have been continued. */
1230 continue;
1231
1232 case 'B':
1233 if ((r = sshbuf_putf(berr,
1234 "%cB\r\n", efc->escape_char)) != 0)
1235 fatal_fr(r, "sshbuf_putf");
1236 channel_request_start(ssh, c->self, "break", 0);
1237 if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
1238 (r = sshpkt_send(ssh)) != 0)
1239 fatal_fr(r, "send packet");
1240 continue;
1241
1242 case 'I':
1243 if ((r = sshbuf_putf(berr, "%cI\r\n",
1244 efc->escape_char)) != 0)
1245 fatal_fr(r, "sshbuf_putf");
1246 s = connection_info_message(ssh);
1247 if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1248 fatal_fr(r, "sshbuf_put");
1249 free(s);
1250 continue;
1251
1252 case 'R':
1253 if (ssh->compat & SSH_BUG_NOREKEY)
1254 logit("Server does not "
1255 "support re-keying");
1256 else
1257 need_rekeying = 1;
1258 continue;
1259
1260 case 'V':
1261 /* FALLTHROUGH */
1262 case 'v':
1263 if (c && c->ctl_chan != -1)
1264 goto noescape;
1265 if (!log_is_on_stderr()) {
1266 if ((r = sshbuf_putf(berr,
1267 "%c%c [Logging to syslog]\r\n",
1268 efc->escape_char, ch)) != 0)
1269 fatal_fr(r, "sshbuf_putf");
1270 continue;
1271 }
1272 if (ch == 'V' && options.log_level >
1273 SYSLOG_LEVEL_QUIET)
1274 log_change_level(--options.log_level);
1275 if (ch == 'v' && options.log_level <
1276 SYSLOG_LEVEL_DEBUG3)
1277 log_change_level(++options.log_level);
1278 if ((r = sshbuf_putf(berr,
1279 "%c%c [LogLevel %s]\r\n",
1280 efc->escape_char, ch,
1281 log_level_name(options.log_level))) != 0)
1282 fatal_fr(r, "sshbuf_putf");
1283 continue;
1284
1285 case '&':
1286 if (c->ctl_chan != -1)
1287 goto noescape;
1288 /*
1289 * Detach the program (continue to serve
1290 * connections, but put in background and no
1291 * more new connections).
1292 */
1293 /* Restore tty modes. */
1294 leave_raw_mode(
1295 options.request_tty == REQUEST_TTY_FORCE);
1296
1297 /* Stop listening for new connections. */
1298 channel_stop_listening(ssh);
1299
1300 if ((r = sshbuf_putf(berr, "%c& "
1301 "[backgrounded]\n", efc->escape_char)) != 0)
1302 fatal_fr(r, "sshbuf_putf");
1303
1304 /* Fork into background. */
1305 pid = fork();
1306 if (pid == -1) {
1307 error("fork: %.100s", strerror(errno));
1308 continue;
1309 }
1310 if (pid != 0) { /* This is the parent. */
1311 /* The parent just exits. */
1312 exit(0);
1313 }
1314 /* The child continues serving connections. */
1315 /* fake EOF on stdin */
1316 if ((r = sshbuf_put_u8(bin, 4)) != 0)
1317 fatal_fr(r, "sshbuf_put_u8");
1318 return -1;
1319 case '?':
1320 print_escape_help(berr, efc->escape_char,
1321 (c && c->ctl_chan != -1),
1322 log_is_on_stderr());
1323 continue;
1324
1325 case '#':
1326 if ((r = sshbuf_putf(berr, "%c#\r\n",
1327 efc->escape_char)) != 0)
1328 fatal_fr(r, "sshbuf_putf");
1329 s = channel_open_message(ssh);
1330 if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1331 fatal_fr(r, "sshbuf_put");
1332 free(s);
1333 continue;
1334
1335 case 'C':
1336 if (c && c->ctl_chan != -1)
1337 goto noescape;
1338 if (options.enable_escape_commandline == 0) {
1339 if ((r = sshbuf_putf(berr,
1340 "commandline disabled\r\n")) != 0)
1341 fatal_fr(r, "sshbuf_putf");
1342 continue;
1343 }
1344 process_cmdline(ssh);
1345 continue;
1346
1347 default:
1348 if (ch != efc->escape_char) {
1349 if ((r = sshbuf_put_u8(bin,
1350 efc->escape_char)) != 0)
1351 fatal_fr(r, "sshbuf_put_u8");
1352 bytes++;
1353 }
1354 /* Escaped characters fall through here */
1355 break;
1356 }
1357 } else {
1358 /*
1359 * The previous character was not an escape char.
1360 * Check if this is an escape.
1361 */
1362 if (last_was_cr && ch == efc->escape_char) {
1363 /*
1364 * It is. Set the flag and continue to
1365 * next character.
1366 */
1367 efc->escape_pending = 1;
1368 continue;
1369 }
1370 }
1371
1372 /*
1373 * Normal character. Record whether it was a newline,
1374 * and append it to the buffer.
1375 */
1376 last_was_cr = (ch == '\r' || ch == '\n');
1377 if ((r = sshbuf_put_u8(bin, ch)) != 0)
1378 fatal_fr(r, "sshbuf_put_u8");
1379 bytes++;
1380 }
1381 return bytes;
1382}
1383
1384/*
1385 * Get packets from the connection input buffer, and process them as long as
1386 * there are packets available.
1387 *
1388 * Any unknown packets received during the actual
1389 * session cause the session to terminate. This is
1390 * intended to make debugging easier since no
1391 * confirmations are sent. Any compatible protocol
1392 * extensions must be negotiated during the
1393 * preparatory phase.
1394 */
1395
1396static void
1397client_process_buffered_input_packets(struct ssh *ssh)
1398{
1399 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending);
1400}
1401
1402/* scan buf[] for '~' before sending data to the peer */
1403
1404/* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1405void *
1406client_new_escape_filter_ctx(int escape_char)
1407{
1408 struct escape_filter_ctx *ret;
1409
1410 ret = xcalloc(1, sizeof(*ret));
1411 ret->escape_pending = 0;
1412 ret->escape_char = escape_char;
1413 return (void *)ret;
1414}
1415
1416/* Free the escape filter context on channel free */
1417void
1418client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1419{
1420 free(ctx);
1421}
1422
1423int
1424client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1425{
1426 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1427 return 0;
1428
1429 return process_escapes(ssh, c, c->input, c->output, c->extended,
1430 buf, len);
1431}
1432
1433static void
1434client_channel_closed(struct ssh *ssh, int id, int force, void *arg)
1435{
1436 channel_cancel_cleanup(ssh, id);
1437 session_closed = 1;
1438 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1439}
1440
1441/*
1442 * Implements the interactive session with the server. This is called after
1443 * the user has been authenticated, and a command has been started on the
1444 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1445 * used as an escape character for terminating or suspending the session.
1446 */
1447int
1448client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1449 int ssh2_chan_id)
1450{
1451 struct pollfd *pfd = NULL;
1452 u_int npfd_alloc = 0, npfd_active = 0;
1453 double start_time, total_time;
1454 int interactive = -1, channel_did_enqueue = 0, r;
1455 u_int64_t ibytes, obytes;
1456 int conn_in_ready, conn_out_ready;
1457 sigset_t bsigset, osigset;
1458
1459 debug("Entering interactive session.");
1460 session_ident = ssh2_chan_id;
1461
1462 if (options.pkcs11_provider != NULL)
1463 debug("pledge: disabled (PKCS11Provider active)");
1464 else if (options.control_master &&
1465 !option_clear_or_none(options.control_path)) {
1466 debug("pledge: id");
1467 if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty",
1468 NULL) == -1)
1469 fatal_f("pledge(): %s", strerror(errno));
1470
1471 } else if (options.forward_x11 || options.permit_local_command) {
1472 debug("pledge: exec");
1473 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1474 NULL) == -1)
1475 fatal_f("pledge(): %s", strerror(errno));
1476
1477 } else if (options.update_hostkeys) {
1478 debug("pledge: filesystem");
1479 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1480 NULL) == -1)
1481 fatal_f("pledge(): %s", strerror(errno));
1482
1483 } else if (!option_clear_or_none(options.proxy_command) ||
1484 options.fork_after_authentication) {
1485 debug("pledge: proc");
1486 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1487 fatal_f("pledge(): %s", strerror(errno));
1488
1489 } else {
1490 debug("pledge: network");
1491 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1492 fatal_f("pledge(): %s", strerror(errno));
1493 }
1494
1495 /* might be able to tighten now */
1496 client_repledge();
1497
1498 start_time = monotime_double();
1499
1500 /* Initialize variables. */
1501 last_was_cr = 1;
1502 exit_status = -1;
1503 connection_in = ssh_packet_get_connection_in(ssh);
1504 connection_out = ssh_packet_get_connection_out(ssh);
1505
1506 quit_pending = 0;
1507
1508 client_init_dispatch(ssh);
1509
1510 /*
1511 * Set signal handlers, (e.g. to restore non-blocking mode)
1512 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1513 */
1514 if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1515 ssh_signal(SIGHUP, signal_handler);
1516 if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN)
1517 ssh_signal(SIGINT, signal_handler);
1518 if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1519 ssh_signal(SIGQUIT, signal_handler);
1520 if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN)
1521 ssh_signal(SIGTERM, signal_handler);
1522 ssh_signal(SIGWINCH, window_change_handler);
1523 ssh_signal(SIGINFO, siginfo_handler);
1524
1525 if (have_pty)
1526 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1527
1528 if (session_ident != -1) {
1529 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1530 channel_register_filter(ssh, session_ident,
1531 client_simple_escape_filter, NULL,
1532 client_filter_cleanup,
1533 client_new_escape_filter_ctx(
1534 escape_char_arg));
1535 }
1536 channel_register_cleanup(ssh, session_ident,
1537 client_channel_closed, 0);
1538 }
1539
1540 schedule_server_alive_check();
1541
1542 if (sigemptyset(&bsigset) == -1 ||
1543 sigaddset(&bsigset, SIGHUP) == -1 ||
1544 sigaddset(&bsigset, SIGINT) == -1 ||
1545 sigaddset(&bsigset, SIGQUIT) == -1 ||
1546 sigaddset(&bsigset, SIGTERM) == -1 ||
1547 sigaddset(&bsigset, SIGINFO) == -1)
1548 error_f("bsigset setup: %s", strerror(errno));
1549
1550 /* Main loop of the client for the interactive session mode. */
1551 while (!quit_pending) {
1552 channel_did_enqueue = 0;
1553
1554 /* Process buffered packets sent by the server. */
1555 client_process_buffered_input_packets(ssh);
1556
1557 if (session_closed && !channel_still_open(ssh))
1558 break;
1559
1560 if (ssh_packet_is_rekeying(ssh)) {
1561 debug("rekeying in progress");
1562 } else if (need_rekeying) {
1563 /* manual rekey request */
1564 debug("need rekeying");
1565 if ((r = kex_start_rekex(ssh)) != 0)
1566 fatal_fr(r, "kex_start_rekex");
1567 need_rekeying = 0;
1568 } else {
1569 /*
1570 * Make packets from buffered channel data, and
1571 * enqueue them for sending to the server.
1572 */
1573 if (ssh_packet_not_very_much_data_to_write(ssh))
1574 channel_did_enqueue = channel_output_poll(ssh);
1575
1576 /*
1577 * Check if the window size has changed, and buffer a
1578 * message about it to the server if so.
1579 */
1580 client_check_window_change(ssh);
1581 }
1582 /*
1583 * Wait until we have something to do (something becomes
1584 * available on one of the descriptors).
1585 */
1586 if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1)
1587 error_f("bsigset sigprocmask: %s", strerror(errno));
1588 if (siginfo_received) {
1589 siginfo_received = 0;
1590 channel_report_open(ssh, SYSLOG_LEVEL_INFO);
1591 }
1592 if (quit_pending)
1593 break;
1594 client_wait_until_can_do_something(ssh, &pfd, &npfd_alloc,
1595 &npfd_active, channel_did_enqueue, &osigset,
1596 &conn_in_ready, &conn_out_ready);
1597 if (sigprocmask(SIG_SETMASK, &osigset, NULL) == -1)
1598 error_f("osigset sigprocmask: %s", strerror(errno));
1599
1600 if (quit_pending)
1601 break;
1602
1603 /* Do channel operations. */
1604 channel_after_poll(ssh, pfd, npfd_active);
1605
1606 /* Buffer input from the connection. */
1607 if (conn_in_ready)
1608 client_process_net_input(ssh);
1609
1610 if (quit_pending)
1611 break;
1612
1613 /* A timeout may have triggered rekeying */
1614 if ((r = ssh_packet_check_rekey(ssh)) != 0)
1615 fatal_fr(r, "cannot start rekeying");
1616
1617 /*
1618 * Send as much buffered packet data as possible to the
1619 * sender.
1620 */
1621 if (conn_out_ready) {
1622 if (interactive != !channel_has_bulk(ssh)) {
1623 interactive = !channel_has_bulk(ssh);
1624 debug2_f("session QoS is now %s", interactive ?
1625 "interactive" : "non-interactive");
1626 ssh_packet_set_interactive(ssh, interactive);
1627 }
1628 if ((r = ssh_packet_write_poll(ssh)) != 0) {
1629 sshpkt_fatal(ssh, r,
1630 "%s: ssh_packet_write_poll", __func__);
1631 }
1632 }
1633
1634 /*
1635 * If we are a backgrounded control master, and the
1636 * timeout has expired without any active client
1637 * connections, then quit.
1638 */
1639 if (control_persist_exit_time > 0) {
1640 if (monotime() >= control_persist_exit_time) {
1641 debug("ControlPersist timeout expired");
1642 break;
1643 }
1644 }
1645 }
1646 free(pfd);
1647
1648 /* Terminate the session. */
1649
1650 /*
1651 * In interactive mode (with pseudo tty) display a message indicating
1652 * that the connection has been closed.
1653 */
1654 if (have_pty && options.log_level >= SYSLOG_LEVEL_INFO)
1655 quit_message("Connection to %s closed.", host);
1656
1657
1658 /* Stop watching for window change. */
1659 ssh_signal(SIGWINCH, SIG_DFL);
1660
1661 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
1662 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 ||
1663 (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 ||
1664 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* language tag */
1665 (r = sshpkt_send(ssh)) != 0 ||
1666 (r = ssh_packet_write_wait(ssh)) != 0)
1667 fatal_fr(r, "send disconnect");
1668
1669 channel_free_all(ssh);
1670
1671 if (have_pty)
1672 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1673
1674 /*
1675 * If there was no shell or command requested, there will be no remote
1676 * exit status to be returned. In that case, clear error code if the
1677 * connection was deliberately terminated at this end.
1678 */
1679 if (options.session_type == SESSION_TYPE_NONE &&
1680 received_signal == SIGTERM) {
1681 received_signal = 0;
1682 exit_status = 0;
1683 }
1684
1685 if (received_signal) {
1686 verbose("Killed by signal %d.", (int) received_signal);
1687 cleanup_exit(255);
1688 }
1689
1690 /* Report bytes transferred, and transfer rates. */
1691 total_time = monotime_double() - start_time;
1692 ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1693 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1694 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1695 if (total_time > 0)
1696 verbose("Bytes per second: sent %.1f, received %.1f",
1697 obytes / total_time, ibytes / total_time);
1698 /* Return the exit status of the program. */
1699 debug("Exit status %d", exit_status);
1700 return exit_status;
1701}
1702
1703/*********/
1704
1705static Channel *
1706client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1707 int rchan, u_int rwindow, u_int rmaxpack)
1708{
1709 Channel *c = NULL;
1710 struct sshbuf *b = NULL;
1711 char *listen_address, *originator_address;
1712 u_int listen_port, originator_port;
1713 int r;
1714
1715 /* Get rest of the packet */
1716 if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 ||
1717 (r = sshpkt_get_u32(ssh, &listen_port)) != 0 ||
1718 (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 ||
1719 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1720 (r = sshpkt_get_end(ssh)) != 0)
1721 fatal_fr(r, "parse packet");
1722
1723 debug_f("listen %s port %d, originator %s port %d",
1724 listen_address, listen_port, originator_address, originator_port);
1725
1726 if (listen_port > 0xffff)
1727 error_f("invalid listen port");
1728 else if (originator_port > 0xffff)
1729 error_f("invalid originator port");
1730 else {
1731 c = channel_connect_by_listen_address(ssh,
1732 listen_address, listen_port, "forwarded-tcpip",
1733 originator_address);
1734 }
1735
1736 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1737 if ((b = sshbuf_new()) == NULL) {
1738 error_f("alloc reply");
1739 goto out;
1740 }
1741 /* reconstruct and send to muxclient */
1742 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1743 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1744 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1745 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1746 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1747 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1748 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1749 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1750 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1751 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1752 (r = sshbuf_put_stringb(c->output, b)) != 0) {
1753 error_fr(r, "compose for muxclient");
1754 goto out;
1755 }
1756 }
1757
1758 out:
1759 sshbuf_free(b);
1760 free(originator_address);
1761 free(listen_address);
1762 return c;
1763}
1764
1765static Channel *
1766client_request_forwarded_streamlocal(struct ssh *ssh,
1767 const char *request_type, int rchan)
1768{
1769 Channel *c = NULL;
1770 char *listen_path;
1771 int r;
1772
1773 /* Get the remote path. */
1774 if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 ||
1775 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* reserved */
1776 (r = sshpkt_get_end(ssh)) != 0)
1777 fatal_fr(r, "parse packet");
1778
1779 debug_f("request: %s", listen_path);
1780
1781 c = channel_connect_by_listen_path(ssh, listen_path,
1782 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1783 free(listen_path);
1784 return c;
1785}
1786
1787static Channel *
1788client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1789{
1790 Channel *c = NULL;
1791 char *originator;
1792 u_int originator_port;
1793 int r, sock;
1794
1795 if (!options.forward_x11) {
1796 error("Warning: ssh server tried X11 forwarding.");
1797 error("Warning: this is probably a break-in attempt by a "
1798 "malicious server.");
1799 return NULL;
1800 }
1801 if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) {
1802 verbose("Rejected X11 connection after ForwardX11Timeout "
1803 "expired");
1804 return NULL;
1805 }
1806 if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
1807 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1808 (r = sshpkt_get_end(ssh)) != 0)
1809 fatal_fr(r, "parse packet");
1810 /* XXX check permission */
1811 /* XXX range check originator port? */
1812 debug("client_request_x11: request from %s %u", originator,
1813 originator_port);
1814 free(originator);
1815 sock = x11_connect_display(ssh);
1816 if (sock < 0)
1817 return NULL;
1818 c = channel_new(ssh, "x11-connection",
1819 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1820 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1821 c->force_drain = 1;
1822 return c;
1823}
1824
1825static Channel *
1826client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1827{
1828 Channel *c = NULL;
1829 int r, sock;
1830
1831 if (!options.forward_agent) {
1832 error("Warning: ssh server tried agent forwarding.");
1833 error("Warning: this is probably a break-in attempt by a "
1834 "malicious server.");
1835 return NULL;
1836 }
1837 if (forward_agent_sock_path == NULL) {
1838 r = ssh_get_authentication_socket(&sock);
1839 } else {
1840 r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock);
1841 }
1842 if (r != 0) {
1843 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1844 debug_fr(r, "ssh_get_authentication_socket");
1845 return NULL;
1846 }
1847 if ((r = ssh_agent_bind_hostkey(sock, ssh->kex->initial_hostkey,
1848 ssh->kex->session_id, ssh->kex->initial_sig, 1)) == 0)
1849 debug_f("bound agent to hostkey");
1850 else
1851 debug2_fr(r, "ssh_agent_bind_hostkey");
1852
1853 c = channel_new(ssh, "agent-connection",
1854 SSH_CHANNEL_OPEN, sock, sock, -1,
1855 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1856 "authentication agent connection", 1);
1857 c->force_drain = 1;
1858 return c;
1859}
1860
1861char *
1862client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1863 int local_tun, int remote_tun, channel_open_fn *cb, void *cbctx)
1864{
1865 Channel *c;
1866 int r, fd;
1867 char *ifname = NULL;
1868
1869 if (tun_mode == SSH_TUNMODE_NO)
1870 return NULL;
1871
1872 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1873
1874 /* Open local tunnel device */
1875 if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1876 error("Tunnel device open failed.");
1877 return NULL;
1878 }
1879 debug("Tunnel forwarding using interface %s", ifname);
1880
1881 c = channel_new(ssh, "tun-connection", SSH_CHANNEL_OPENING, fd, fd, -1,
1882 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1883 c->datagram = 1;
1884
1885 if (cb != NULL)
1886 channel_register_open_confirm(ssh, c->self, cb, cbctx);
1887
1888 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1889 (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 ||
1890 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1891 (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 ||
1892 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1893 (r = sshpkt_put_u32(ssh, tun_mode)) != 0 ||
1894 (r = sshpkt_put_u32(ssh, remote_tun)) != 0 ||
1895 (r = sshpkt_send(ssh)) != 0)
1896 sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1897
1898 return ifname;
1899}
1900
1901/* XXXX move to generic input handler */
1902static int
1903client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1904{
1905 Channel *c = NULL;
1906 char *ctype = NULL;
1907 int r;
1908 u_int rchan;
1909 size_t len;
1910 u_int rmaxpack, rwindow;
1911
1912 if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 ||
1913 (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
1914 (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
1915 (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
1916 goto out;
1917
1918 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1919 ctype, rchan, rwindow, rmaxpack);
1920
1921 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1922 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1923 rmaxpack);
1924 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1925 c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1926 } else if (strcmp(ctype, "x11") == 0) {
1927 c = client_request_x11(ssh, ctype, rchan);
1928 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1929 c = client_request_agent(ssh, ctype, rchan);
1930 }
1931 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1932 debug3("proxied to downstream: %s", ctype);
1933 } else if (c != NULL) {
1934 debug("confirm %s", ctype);
1935 c->remote_id = rchan;
1936 c->have_remote_id = 1;
1937 c->remote_window = rwindow;
1938 c->remote_maxpacket = rmaxpack;
1939 if (c->type != SSH_CHANNEL_CONNECTING) {
1940 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1941 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1942 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1943 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1944 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1945 (r = sshpkt_send(ssh)) != 0)
1946 sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1947 }
1948 } else {
1949 debug("failure %s", ctype);
1950 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1951 (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
1952 (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 ||
1953 (r = sshpkt_put_cstring(ssh, "open failed")) != 0 ||
1954 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1955 (r = sshpkt_send(ssh)) != 0)
1956 sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1957 }
1958 r = 0;
1959 out:
1960 free(ctype);
1961 return r;
1962}
1963
1964static int
1965client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1966{
1967 Channel *c = NULL;
1968 char *rtype = NULL;
1969 u_char reply;
1970 u_int id, exitval;
1971 int r, success = 0;
1972
1973 if ((r = sshpkt_get_u32(ssh, &id)) != 0)
1974 return r;
1975 if (id <= INT_MAX)
1976 c = channel_lookup(ssh, id);
1977 if (channel_proxy_upstream(c, type, seq, ssh))
1978 return 0;
1979 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
1980 (r = sshpkt_get_u8(ssh, &reply)) != 0)
1981 goto out;
1982
1983 debug("client_input_channel_req: channel %u rtype %s reply %d",
1984 id, rtype, reply);
1985
1986 if (c == NULL) {
1987 error("client_input_channel_req: channel %d: "
1988 "unknown channel", id);
1989 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1990 if ((r = sshpkt_get_end(ssh)) != 0)
1991 goto out;
1992 chan_rcvd_eow(ssh, c);
1993 } else if (strcmp(rtype, "exit-status") == 0) {
1994 if ((r = sshpkt_get_u32(ssh, &exitval)) != 0)
1995 goto out;
1996 if (c->ctl_chan != -1) {
1997 mux_exit_message(ssh, c, exitval);
1998 success = 1;
1999 } else if ((int)id == session_ident) {
2000 /* Record exit value of local session */
2001 success = 1;
2002 exit_status = exitval;
2003 } else {
2004 /* Probably for a mux channel that has already closed */
2005 debug_f("no sink for exit-status on channel %d",
2006 id);
2007 }
2008 if ((r = sshpkt_get_end(ssh)) != 0)
2009 goto out;
2010 }
2011 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
2012 if (!c->have_remote_id)
2013 fatal_f("channel %d: no remote_id", c->self);
2014 if ((r = sshpkt_start(ssh, success ?
2015 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
2016 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2017 (r = sshpkt_send(ssh)) != 0)
2018 sshpkt_fatal(ssh, r, "%s: send failure", __func__);
2019 }
2020 r = 0;
2021 out:
2022 free(rtype);
2023 return r;
2024}
2025
2026struct hostkeys_update_ctx {
2027 /* The hostname and (optionally) IP address string for the server */
2028 char *host_str, *ip_str;
2029
2030 /*
2031 * Keys received from the server and a flag for each indicating
2032 * whether they already exist in known_hosts.
2033 * keys_match is filled in by hostkeys_find() and later (for new
2034 * keys) by client_global_hostkeys_prove_confirm().
2035 */
2036 struct sshkey **keys;
2037 u_int *keys_match; /* mask of HKF_MATCH_* from hostfile.h */
2038 int *keys_verified; /* flag for new keys verified by server */
2039 size_t nkeys, nnew, nincomplete; /* total, new keys, incomplete match */
2040
2041 /*
2042 * Keys that are in known_hosts, but were not present in the update
2043 * from the server (i.e. scheduled to be deleted).
2044 * Filled in by hostkeys_find().
2045 */
2046 struct sshkey **old_keys;
2047 size_t nold;
2048
2049 /* Various special cases. */
2050 int complex_hostspec; /* wildcard or manual pattern-list host name */
2051 int ca_available; /* saw CA key for this host */
2052 int old_key_seen; /* saw old key with other name/addr */
2053 int other_name_seen; /* saw key with other name/addr */
2054};
2055
2056static void
2057hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
2058{
2059 size_t i;
2060
2061 if (ctx == NULL)
2062 return;
2063 for (i = 0; i < ctx->nkeys; i++)
2064 sshkey_free(ctx->keys[i]);
2065 free(ctx->keys);
2066 free(ctx->keys_match);
2067 free(ctx->keys_verified);
2068 for (i = 0; i < ctx->nold; i++)
2069 sshkey_free(ctx->old_keys[i]);
2070 free(ctx->old_keys);
2071 free(ctx->host_str);
2072 free(ctx->ip_str);
2073 free(ctx);
2074}
2075
2076/*
2077 * Returns non-zero if a known_hosts hostname list is not of a form that
2078 * can be handled by UpdateHostkeys. These include wildcard hostnames and
2079 * hostnames lists that do not follow the form host[,ip].
2080 */
2081static int
2082hostspec_is_complex(const char *hosts)
2083{
2084 char *cp;
2085
2086 /* wildcard */
2087 if (strchr(hosts, '*') != NULL || strchr(hosts, '?') != NULL)
2088 return 1;
2089 /* single host/ip = ok */
2090 if ((cp = strchr(hosts, ',')) == NULL)
2091 return 0;
2092 /* more than two entries on the line */
2093 if (strchr(cp + 1, ',') != NULL)
2094 return 1;
2095 /* XXX maybe parse cp+1 and ensure it is an IP? */
2096 return 0;
2097}
2098
2099/* callback to search for ctx->keys in known_hosts */
2100static int
2101hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
2102{
2103 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2104 size_t i;
2105 struct sshkey **tmp;
2106
2107 if (l->key == NULL)
2108 return 0;
2109 if (l->status != HKF_STATUS_MATCHED) {
2110 /* Record if one of the keys appears on a non-matching line */
2111 for (i = 0; i < ctx->nkeys; i++) {
2112 if (sshkey_equal(l->key, ctx->keys[i])) {
2113 ctx->other_name_seen = 1;
2114 debug3_f("found %s key under different "
2115 "name/addr at %s:%ld",
2116 sshkey_ssh_name(ctx->keys[i]),
2117 l->path, l->linenum);
2118 return 0;
2119 }
2120 }
2121 return 0;
2122 }
2123 /* Don't proceed if revocation or CA markers are present */
2124 /* XXX relax this */
2125 if (l->marker != MRK_NONE) {
2126 debug3_f("hostkeys file %s:%ld has CA/revocation marker",
2127 l->path, l->linenum);
2128 ctx->complex_hostspec = 1;
2129 return 0;
2130 }
2131
2132 /* If CheckHostIP is enabled, then check for mismatched hostname/addr */
2133 if (ctx->ip_str != NULL && strchr(l->hosts, ',') != NULL) {
2134 if ((l->match & HKF_MATCH_HOST) == 0) {
2135 /* Record if address matched a different hostname. */
2136 ctx->other_name_seen = 1;
2137 debug3_f("found address %s against different hostname "
2138 "at %s:%ld", ctx->ip_str, l->path, l->linenum);
2139 return 0;
2140 } else if ((l->match & HKF_MATCH_IP) == 0) {
2141 /* Record if hostname matched a different address. */
2142 ctx->other_name_seen = 1;
2143 debug3_f("found hostname %s against different address "
2144 "at %s:%ld", ctx->host_str, l->path, l->linenum);
2145 }
2146 }
2147
2148 /*
2149 * UpdateHostkeys is skipped for wildcard host names and hostnames
2150 * that contain more than two entries (ssh never writes these).
2151 */
2152 if (hostspec_is_complex(l->hosts)) {
2153 debug3_f("hostkeys file %s:%ld complex host specification",
2154 l->path, l->linenum);
2155 ctx->complex_hostspec = 1;
2156 return 0;
2157 }
2158
2159 /* Mark off keys we've already seen for this host */
2160 for (i = 0; i < ctx->nkeys; i++) {
2161 if (!sshkey_equal(l->key, ctx->keys[i]))
2162 continue;
2163 debug3_f("found %s key at %s:%ld",
2164 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
2165 ctx->keys_match[i] |= l->match;
2166 return 0;
2167 }
2168 /* This line contained a key that not offered by the server */
2169 debug3_f("deprecated %s key at %s:%ld", sshkey_ssh_name(l->key),
2170 l->path, l->linenum);
2171 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
2172 sizeof(*ctx->old_keys))) == NULL)
2173 fatal_f("recallocarray failed nold = %zu", ctx->nold);
2174 ctx->old_keys = tmp;
2175 ctx->old_keys[ctx->nold++] = l->key;
2176 l->key = NULL;
2177
2178 return 0;
2179}
2180
2181/* callback to search for ctx->old_keys in known_hosts under other names */
2182static int
2183hostkeys_check_old(struct hostkey_foreach_line *l, void *_ctx)
2184{
2185 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2186 size_t i;
2187 int hashed;
2188
2189 /* only care about lines that *don't* match the active host spec */
2190 if (l->status == HKF_STATUS_MATCHED || l->key == NULL)
2191 return 0;
2192
2193 hashed = l->match & (HKF_MATCH_HOST_HASHED|HKF_MATCH_IP_HASHED);
2194 for (i = 0; i < ctx->nold; i++) {
2195 if (!sshkey_equal(l->key, ctx->old_keys[i]))
2196 continue;
2197 debug3_f("found deprecated %s key at %s:%ld as %s",
2198 sshkey_ssh_name(ctx->old_keys[i]), l->path, l->linenum,
2199 hashed ? "[HASHED]" : l->hosts);
2200 ctx->old_key_seen = 1;
2201 break;
2202 }
2203 return 0;
2204}
2205
2206/*
2207 * Check known_hosts files for deprecated keys under other names. Returns 0
2208 * on success or -1 on failure. Updates ctx->old_key_seen if deprecated keys
2209 * exist under names other than the active hostname/IP.
2210 */
2211static int
2212check_old_keys_othernames(struct hostkeys_update_ctx *ctx)
2213{
2214 size_t i;
2215 int r;
2216
2217 debug2_f("checking for %zu deprecated keys", ctx->nold);
2218 for (i = 0; i < options.num_user_hostfiles; i++) {
2219 debug3_f("searching %s for %s / %s",
2220 options.user_hostfiles[i], ctx->host_str,
2221 ctx->ip_str ? ctx->ip_str : "(none)");
2222 if ((r = hostkeys_foreach(options.user_hostfiles[i],
2223 hostkeys_check_old, ctx, ctx->host_str, ctx->ip_str,
2224 HKF_WANT_PARSE_KEY, 0)) != 0) {
2225 if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
2226 debug_f("hostkeys file %s does not exist",
2227 options.user_hostfiles[i]);
2228 continue;
2229 }
2230 error_fr(r, "hostkeys_foreach failed for %s",
2231 options.user_hostfiles[i]);
2232 return -1;
2233 }
2234 }
2235 return 0;
2236}
2237
2238static void
2239hostkey_change_preamble(LogLevel loglevel)
2240{
2241 do_log2(loglevel, "The server has updated its host keys.");
2242 do_log2(loglevel, "These changes were verified by the server's "
2243 "existing trusted key.");
2244}
2245
2246static void
2247update_known_hosts(struct hostkeys_update_ctx *ctx)
2248{
2249 int r, was_raw = 0, first = 1;
2250 int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK;
2251 LogLevel loglevel = asking ? SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
2252 char *fp, *response;
2253 size_t i;
2254 struct stat sb;
2255
2256 for (i = 0; i < ctx->nkeys; i++) {
2257 if (!ctx->keys_verified[i])
2258 continue;
2259 if ((fp = sshkey_fingerprint(ctx->keys[i],
2260 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2261 fatal_f("sshkey_fingerprint failed");
2262 if (first && asking)
2263 hostkey_change_preamble(loglevel);
2264 do_log2(loglevel, "Learned new hostkey: %s %s",
2265 sshkey_type(ctx->keys[i]), fp);
2266 first = 0;
2267 free(fp);
2268 }
2269 for (i = 0; i < ctx->nold; i++) {
2270 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
2271 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2272 fatal_f("sshkey_fingerprint failed");
2273 if (first && asking)
2274 hostkey_change_preamble(loglevel);
2275 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
2276 sshkey_type(ctx->old_keys[i]), fp);
2277 first = 0;
2278 free(fp);
2279 }
2280 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
2281 if (get_saved_tio() != NULL) {
2282 leave_raw_mode(1);
2283 was_raw = 1;
2284 }
2285 response = NULL;
2286 for (i = 0; !quit_pending && i < 3; i++) {
2287 free(response);
2288 response = read_passphrase("Accept updated hostkeys? "
2289 "(yes/no): ", RP_ECHO);
2290 if (response != NULL && strcasecmp(response, "yes") == 0)
2291 break;
2292 else if (quit_pending || response == NULL ||
2293 strcasecmp(response, "no") == 0) {
2294 options.update_hostkeys = 0;
2295 break;
2296 } else {
2297 do_log2(loglevel, "Please enter "
2298 "\"yes\" or \"no\"");
2299 }
2300 }
2301 if (quit_pending || i >= 3 || response == NULL)
2302 options.update_hostkeys = 0;
2303 free(response);
2304 if (was_raw)
2305 enter_raw_mode(1);
2306 }
2307 if (options.update_hostkeys == 0)
2308 return;
2309 /*
2310 * Now that all the keys are verified, we can go ahead and replace
2311 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
2312 * cancel the operation).
2313 */
2314 for (i = 0; i < options.num_user_hostfiles; i++) {
2315 /*
2316 * NB. keys are only added to hostfiles[0], for the rest we
2317 * just delete the hostname entries.
2318 */
2319 if (stat(options.user_hostfiles[i], &sb) != 0) {
2320 if (errno == ENOENT) {
2321 debug_f("known hosts file %s does not "
2322 "exist", options.user_hostfiles[i]);
2323 } else {
2324 error_f("known hosts file %s "
2325 "inaccessible: %s",
2326 options.user_hostfiles[i], strerror(errno));
2327 }
2328 continue;
2329 }
2330 if ((r = hostfile_replace_entries(options.user_hostfiles[i],
2331 ctx->host_str, ctx->ip_str,
2332 i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0,
2333 options.hash_known_hosts, 0,
2334 options.fingerprint_hash)) != 0) {
2335 error_fr(r, "hostfile_replace_entries failed for %s",
2336 options.user_hostfiles[i]);
2337 }
2338 }
2339}
2340
2341static void
2342client_global_hostkeys_prove_confirm(struct ssh *ssh, int type,
2343 u_int32_t seq, void *_ctx)
2344{
2345 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2346 size_t i, ndone;
2347 struct sshbuf *signdata;
2348 int r, plaintype;
2349 const u_char *sig;
2350 const char *rsa_kexalg = NULL;
2351 char *alg = NULL;
2352 size_t siglen;
2353
2354 if (ctx->nnew == 0)
2355 fatal_f("ctx->nnew == 0"); /* sanity */
2356 if (type != SSH2_MSG_REQUEST_SUCCESS) {
2357 error("Server failed to confirm ownership of "
2358 "private host keys");
2359 hostkeys_update_ctx_free(ctx);
2360 return;
2361 }
2362 if (sshkey_type_plain(sshkey_type_from_name(
2363 ssh->kex->hostkey_alg)) == KEY_RSA)
2364 rsa_kexalg = ssh->kex->hostkey_alg;
2365 if ((signdata = sshbuf_new()) == NULL)
2366 fatal_f("sshbuf_new failed");
2367 /*
2368 * Expect a signature for each of the ctx->nnew private keys we
2369 * haven't seen before. They will be in the same order as the
2370 * ctx->keys where the corresponding ctx->keys_match[i] == 0.
2371 */
2372 for (ndone = i = 0; i < ctx->nkeys; i++) {
2373 if (ctx->keys_match[i])
2374 continue;
2375 plaintype = sshkey_type_plain(ctx->keys[i]->type);
2376 /* Prepare data to be signed: session ID, unique string, key */
2377 sshbuf_reset(signdata);
2378 if ( (r = sshbuf_put_cstring(signdata,
2379 "hostkeys-prove-00@openssh.com")) != 0 ||
2380 (r = sshbuf_put_stringb(signdata,
2381 ssh->kex->session_id)) != 0 ||
2382 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
2383 fatal_fr(r, "compose signdata");
2384 /* Extract and verify signature */
2385 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
2386 error_fr(r, "parse sig");
2387 goto out;
2388 }
2389 if ((r = sshkey_get_sigtype(sig, siglen, &alg)) != 0) {
2390 error_fr(r, "server gave unintelligible signature "
2391 "for %s key %zu", sshkey_type(ctx->keys[i]), i);
2392 goto out;
2393 }
2394 /*
2395 * Special case for RSA keys: if a RSA hostkey was negotiated,
2396 * then use its signature type for verification of RSA hostkey
2397 * proofs. Otherwise, accept only RSA-SHA256/512 signatures.
2398 */
2399 if (plaintype == KEY_RSA && rsa_kexalg == NULL &&
2400 match_pattern_list(alg, HOSTKEY_PROOF_RSA_ALGS, 0) != 1) {
2401 debug_f("server used untrusted RSA signature algorithm "
2402 "%s for key %zu, disregarding", alg, i);
2403 free(alg);
2404 /* zap the key from the list */
2405 sshkey_free(ctx->keys[i]);
2406 ctx->keys[i] = NULL;
2407 ndone++;
2408 continue;
2409 }
2410 debug3_f("verify %s key %zu using sigalg %s",
2411 sshkey_type(ctx->keys[i]), i, alg);
2412 free(alg);
2413 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
2414 sshbuf_ptr(signdata), sshbuf_len(signdata),
2415 plaintype == KEY_RSA ? rsa_kexalg : NULL, 0, NULL)) != 0) {
2416 error_fr(r, "server gave bad signature for %s key %zu",
2417 sshkey_type(ctx->keys[i]), i);
2418 goto out;
2419 }
2420 /* Key is good. Mark it as 'seen' */
2421 ctx->keys_verified[i] = 1;
2422 ndone++;
2423 }
2424 /* Shouldn't happen */
2425 if (ndone != ctx->nnew)
2426 fatal_f("ndone != ctx->nnew (%zu / %zu)", ndone, ctx->nnew);
2427 if ((r = sshpkt_get_end(ssh)) != 0) {
2428 error_f("protocol error");
2429 goto out;
2430 }
2431
2432 /* Make the edits to known_hosts */
2433 update_known_hosts(ctx);
2434 out:
2435 sshbuf_free(signdata);
2436 hostkeys_update_ctx_free(ctx);
2437 hostkeys_update_complete = 1;
2438 client_repledge();
2439}
2440
2441/*
2442 * Handle hostkeys-00@openssh.com global request to inform the client of all
2443 * the server's hostkeys. The keys are checked against the user's
2444 * HostkeyAlgorithms preference before they are accepted.
2445 */
2446static int
2447client_input_hostkeys(struct ssh *ssh)
2448{
2449 const u_char *blob = NULL;
2450 size_t i, len = 0;
2451 struct sshbuf *buf = NULL;
2452 struct sshkey *key = NULL, **tmp;
2453 int r, prove_sent = 0;
2454 char *fp;
2455 static int hostkeys_seen = 0; /* XXX use struct ssh */
2456 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2457 struct hostkeys_update_ctx *ctx = NULL;
2458 u_int want;
2459
2460 if (hostkeys_seen)
2461 fatal_f("server already sent hostkeys");
2462 if (!can_update_hostkeys())
2463 return 1;
2464 hostkeys_seen = 1;
2465
2466 ctx = xcalloc(1, sizeof(*ctx));
2467 while (ssh_packet_remaining(ssh) > 0) {
2468 sshkey_free(key);
2469 key = NULL;
2470 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2471 error_fr(r, "parse key");
2472 goto out;
2473 }
2474 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2475 do_log2_fr(r, r == SSH_ERR_KEY_TYPE_UNKNOWN ?
2476 SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR,
2477 "convert key");
2478 continue;
2479 }
2480 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2481 SSH_FP_DEFAULT);
2482 debug3_f("received %s key %s", sshkey_type(key), fp);
2483 free(fp);
2484
2485 if (!hostkey_accepted_by_hostkeyalgs(key)) {
2486 debug3_f("%s key not permitted by "
2487 "HostkeyAlgorithms", sshkey_ssh_name(key));
2488 continue;
2489 }
2490 /* Skip certs */
2491 if (sshkey_is_cert(key)) {
2492 debug3_f("%s key is a certificate; skipping",
2493 sshkey_ssh_name(key));
2494 continue;
2495 }
2496 /* Ensure keys are unique */
2497 for (i = 0; i < ctx->nkeys; i++) {
2498 if (sshkey_equal(key, ctx->keys[i])) {
2499 error_f("received duplicated %s host key",
2500 sshkey_ssh_name(key));
2501 goto out;
2502 }
2503 }
2504 /* Key is good, record it */
2505 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
2506 sizeof(*ctx->keys))) == NULL)
2507 fatal_f("recallocarray failed nkeys = %zu",
2508 ctx->nkeys);
2509 ctx->keys = tmp;
2510 ctx->keys[ctx->nkeys++] = key;
2511 key = NULL;
2512 }
2513
2514 if (ctx->nkeys == 0) {
2515 debug_f("server sent no hostkeys");
2516 goto out;
2517 }
2518
2519 if ((ctx->keys_match = calloc(ctx->nkeys,
2520 sizeof(*ctx->keys_match))) == NULL ||
2521 (ctx->keys_verified = calloc(ctx->nkeys,
2522 sizeof(*ctx->keys_verified))) == NULL)
2523 fatal_f("calloc failed");
2524
2525 get_hostfile_hostname_ipaddr(host,
2526 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2527 options.port, &ctx->host_str,
2528 options.check_host_ip ? &ctx->ip_str : NULL);
2529
2530 /* Find which keys we already know about. */
2531 for (i = 0; i < options.num_user_hostfiles; i++) {
2532 debug_f("searching %s for %s / %s",
2533 options.user_hostfiles[i], ctx->host_str,
2534 ctx->ip_str ? ctx->ip_str : "(none)");
2535 if ((r = hostkeys_foreach(options.user_hostfiles[i],
2536 hostkeys_find, ctx, ctx->host_str, ctx->ip_str,
2537 HKF_WANT_PARSE_KEY, 0)) != 0) {
2538 if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
2539 debug_f("hostkeys file %s does not exist",
2540 options.user_hostfiles[i]);
2541 continue;
2542 }
2543 error_fr(r, "hostkeys_foreach failed for %s",
2544 options.user_hostfiles[i]);
2545 goto out;
2546 }
2547 }
2548
2549 /* Figure out if we have any new keys to add */
2550 ctx->nnew = ctx->nincomplete = 0;
2551 want = HKF_MATCH_HOST | ( options.check_host_ip ? HKF_MATCH_IP : 0);
2552 for (i = 0; i < ctx->nkeys; i++) {
2553 if (ctx->keys_match[i] == 0)
2554 ctx->nnew++;
2555 if ((ctx->keys_match[i] & want) != want)
2556 ctx->nincomplete++;
2557 }
2558
2559 debug3_f("%zu server keys: %zu new, %zu retained, "
2560 "%zu incomplete match. %zu to remove", ctx->nkeys, ctx->nnew,
2561 ctx->nkeys - ctx->nnew - ctx->nincomplete,
2562 ctx->nincomplete, ctx->nold);
2563
2564 if (ctx->nnew == 0 && ctx->nold == 0) {
2565 debug_f("no new or deprecated keys from server");
2566 goto out;
2567 }
2568
2569 /* Various reasons why we cannot proceed with the update */
2570 if (ctx->complex_hostspec) {
2571 debug_f("CA/revocation marker, manual host list or wildcard "
2572 "host pattern found, skipping UserKnownHostsFile update");
2573 goto out;
2574 }
2575 if (ctx->other_name_seen) {
2576 debug_f("host key found matching a different name/address, "
2577 "skipping UserKnownHostsFile update");
2578 goto out;
2579 }
2580 /*
2581 * If removing keys, check whether they appear under different
2582 * names/addresses and refuse to proceed if they do. This avoids
2583 * cases such as hosts with multiple names becoming inconsistent
2584 * with regards to CheckHostIP entries.
2585 * XXX UpdateHostkeys=force to override this (and other) checks?
2586 */
2587 if (ctx->nold != 0) {
2588 if (check_old_keys_othernames(ctx) != 0)
2589 goto out; /* error already logged */
2590 if (ctx->old_key_seen) {
2591 debug_f("key(s) for %s%s%s exist under other names; "
2592 "skipping UserKnownHostsFile update",
2593 ctx->host_str, ctx->ip_str == NULL ? "" : ",",
2594 ctx->ip_str == NULL ? "" : ctx->ip_str);
2595 goto out;
2596 }
2597 }
2598
2599 if (ctx->nnew == 0) {
2600 /*
2601 * We have some keys to remove or fix matching for.
2602 * We can proceed to do this without requiring a fresh proof
2603 * from the server.
2604 */
2605 update_known_hosts(ctx);
2606 goto out;
2607 }
2608 /*
2609 * We have received previously-unseen keys from the server.
2610 * Ask the server to confirm ownership of the private halves.
2611 */
2612 debug3_f("asking server to prove ownership for %zu keys", ctx->nnew);
2613 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2614 (r = sshpkt_put_cstring(ssh,
2615 "hostkeys-prove-00@openssh.com")) != 0 ||
2616 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2617 fatal_fr(r, "prepare hostkeys-prove");
2618 if ((buf = sshbuf_new()) == NULL)
2619 fatal_f("sshbuf_new");
2620 for (i = 0; i < ctx->nkeys; i++) {
2621 if (ctx->keys_match[i])
2622 continue;
2623 sshbuf_reset(buf);
2624 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0 ||
2625 (r = sshpkt_put_stringb(ssh, buf)) != 0)
2626 fatal_fr(r, "assemble hostkeys-prove");
2627 }
2628 if ((r = sshpkt_send(ssh)) != 0)
2629 fatal_fr(r, "send hostkeys-prove");
2630 client_register_global_confirm(
2631 client_global_hostkeys_prove_confirm, ctx);
2632 ctx = NULL; /* will be freed in callback */
2633 prove_sent = 1;
2634
2635 /* Success */
2636 out:
2637 hostkeys_update_ctx_free(ctx);
2638 sshkey_free(key);
2639 sshbuf_free(buf);
2640 if (!prove_sent) {
2641 /* UpdateHostkeys handling completed */
2642 hostkeys_update_complete = 1;
2643 client_repledge();
2644 }
2645 /*
2646 * NB. Return success for all cases. The server doesn't need to know
2647 * what the client does with its hosts file.
2648 */
2649 return 1;
2650}
2651
2652static int
2653client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
2654{
2655 char *rtype;
2656 u_char want_reply;
2657 int r, success = 0;
2658
2659 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
2660 (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
2661 goto out;
2662 debug("client_input_global_request: rtype %s want_reply %d",
2663 rtype, want_reply);
2664 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2665 success = client_input_hostkeys(ssh);
2666 if (want_reply) {
2667 if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS :
2668 SSH2_MSG_REQUEST_FAILURE)) != 0 ||
2669 (r = sshpkt_send(ssh)) != 0 ||
2670 (r = ssh_packet_write_wait(ssh)) != 0)
2671 goto out;
2672 }
2673 r = 0;
2674 out:
2675 free(rtype);
2676 return r;
2677}
2678
2679static void
2680client_send_env(struct ssh *ssh, int id, const char *name, const char *val)
2681{
2682 int r;
2683
2684 debug("channel %d: setting env %s = \"%s\"", id, name, val);
2685 channel_request_start(ssh, id, "env", 0);
2686 if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
2687 (r = sshpkt_put_cstring(ssh, val)) != 0 ||
2688 (r = sshpkt_send(ssh)) != 0)
2689 fatal_fr(r, "send setenv");
2690}
2691
2692void
2693client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
2694 const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
2695 char **env)
2696{
2697 size_t i, j, len;
2698 int matched, r;
2699 char *name, *val;
2700 Channel *c = NULL;
2701
2702 debug2_f("id %d", id);
2703
2704 if ((c = channel_lookup(ssh, id)) == NULL)
2705 fatal_f("channel %d: unknown channel", id);
2706
2707 if (want_tty) {
2708 struct winsize ws;
2709
2710 /* Store window size in the packet. */
2711 if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1)
2712 memset(&ws, 0, sizeof(ws));
2713
2714 channel_request_start(ssh, id, "pty-req", 1);
2715 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
2716 if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : ""))
2717 != 0 ||
2718 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
2719 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
2720 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
2721 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0)
2722 fatal_fr(r, "build pty-req");
2723 if (tiop == NULL)
2724 tiop = get_saved_tio();
2725 ssh_tty_make_modes(ssh, -1, tiop);
2726 if ((r = sshpkt_send(ssh)) != 0)
2727 fatal_fr(r, "send pty-req");
2728 /* XXX wait for reply */
2729 c->client_tty = 1;
2730 }
2731
2732 /* Transfer any environment variables from client to server */
2733 if (options.num_send_env != 0 && env != NULL) {
2734 debug("Sending environment.");
2735 for (i = 0; env[i] != NULL; i++) {
2736 /* Split */
2737 name = xstrdup(env[i]);
2738 if ((val = strchr(name, '=')) == NULL) {
2739 free(name);
2740 continue;
2741 }
2742 *val++ = '\0';
2743
2744 matched = 0;
2745 for (j = 0; j < options.num_send_env; j++) {
2746 if (match_pattern(name, options.send_env[j])) {
2747 matched = 1;
2748 break;
2749 }
2750 }
2751 if (!matched) {
2752 debug3("Ignored env %s", name);
2753 free(name);
2754 continue;
2755 }
2756 client_send_env(ssh, id, name, val);
2757 free(name);
2758 }
2759 }
2760 for (i = 0; i < options.num_setenv; i++) {
2761 /* Split */
2762 name = xstrdup(options.setenv[i]);
2763 if ((val = strchr(name, '=')) == NULL) {
2764 free(name);
2765 continue;
2766 }
2767 *val++ = '\0';
2768 client_send_env(ssh, id, name, val);
2769 free(name);
2770 }
2771
2772 len = sshbuf_len(cmd);
2773 if (len > 0) {
2774 if (len > 900)
2775 len = 900;
2776 if (want_subsystem) {
2777 debug("Sending subsystem: %.*s",
2778 (int)len, (const u_char*)sshbuf_ptr(cmd));
2779 channel_request_start(ssh, id, "subsystem", 1);
2780 client_expect_confirm(ssh, id, "subsystem",
2781 CONFIRM_CLOSE);
2782 } else {
2783 debug("Sending command: %.*s",
2784 (int)len, (const u_char*)sshbuf_ptr(cmd));
2785 channel_request_start(ssh, id, "exec", 1);
2786 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
2787 }
2788 if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 ||
2789 (r = sshpkt_send(ssh)) != 0)
2790 fatal_fr(r, "send command");
2791 } else {
2792 channel_request_start(ssh, id, "shell", 1);
2793 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
2794 if ((r = sshpkt_send(ssh)) != 0)
2795 fatal_fr(r, "send shell");
2796 }
2797
2798 session_setup_complete = 1;
2799 client_repledge();
2800}
2801
2802static void
2803client_init_dispatch(struct ssh *ssh)
2804{
2805 ssh_dispatch_init(ssh, &dispatch_protocol_error);
2806
2807 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2808 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2809 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2810 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2811 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2812 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2813 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2814 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2815 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2816 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2817 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2818 ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2819
2820 /* rekeying */
2821 ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
2822
2823 /* global request reply messages */
2824 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2825 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2826}
2827
2828void
2829client_stop_mux(void)
2830{
2831 if (options.control_path != NULL && muxserver_sock != -1)
2832 unlink(options.control_path);
2833 /*
2834 * If we are in persist mode, or don't have a shell, signal that we
2835 * should close when all active channels are closed.
2836 */
2837 if (options.control_persist || options.session_type == SESSION_TYPE_NONE) {
2838 session_closed = 1;
2839 setproctitle("[stopped mux]");
2840 }
2841}
2842
2843/* client specific fatal cleanup */
2844void
2845cleanup_exit(int i)
2846{
2847 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2848 if (options.control_path != NULL && muxserver_sock != -1)
2849 unlink(options.control_path);
2850 ssh_kill_proxy_command();
2851 _exit(i);
2852}